>

Socket 入门

- 编辑:金沙国际平台登录 -

Socket 入门

int socket(int domain, int type,int protocol)
  • domain :表明大家网络程序所在的主机选取的简报业协会族(AF_UNIX和AF_INET等). AF_UNIX只可以够用于单一的Unix系统经过间通讯,而AF_INET是针对Internet的,因此可以允许在中距离主机之间通讯
  • type :大家互连网程序所接纳的报道左券(SOCK_STREAM,SOCK_DGRAM等) SOCK_STREAM表明大家用的是TCP左券,那样会提供按顺序的,可信赖,双向,面向连接的比特流. SOCK_DGRAM 表明大家用的是UDP公约,那样只会提供定长的,不可靠赖,无连接的通讯.
  • protocol :由于大家内定了type,所以那一个地点大家一般若是用0来顶替就足以了

socket为网络通讯做基本的计划.成功时重回文件描述符,战败时回来-1,看errno可见道出错的详细意况

int bind(int sockfd, struct sockaddr *my_addr, int addrlen)
  • sockfd :是由socket调用重返的文本陈说符.
  • addrlen:是sockaddr组织的长度.
  • my_addr :是一个针对sockaddr的指针. 在中有 sockaddr的概念
struct sockaddr{    unisgned short as_family;    char sa_data[14];};

然则出于系统的包容性,我们一般不要这些头文件,而选择另外多个结构(struct sockaddr_in) 来代替.在中有sockaddr_in的定义

struct sockaddr_in{    unsigned short sin_family;    unsigned short int sin_port;    struct in_addr sin_addr;    unsigned char sin_zero[8];}

俺们第一选择Internet所以sin_family一般为AF_INET,sin_addr设置为INADDR_ANY代表能够和别的的主机通讯,sin_port是大家要监听的端口号.sin_zero[8]是用来填充的. bind将地方的端口同socket再次回到的文本陈诉符捆绑在一齐.中标是再次来到0,退步的情事和socket同样

int listen(int sockfd,int backlog)
  • sockfd:是bind后的文本陈述符.
  • backlog:设置央求排队的最大长度.当有八个顾客端程序和服务端相连时, 使用那几个代表能够介绍的排队长度. listen函数将bind的文件陈述符变为监听套接字.重回的图景和bind同样.
int accept(int sockfd, struct sockaddr *addr,socklen_t *addrlen)
  • sockfd:是listen后的文件陈说符.
  • addr,addrlen是用来给客户端的次序填写的,服务器端只要传递指针就足以了. bind,listen和accept是服务器端用的函数,accept调用时,服务器端的程序会一贯不通到有二个客商程序发出了连接. accept成功时回来最终的劳动器端的文本描述符,那年服务器端可以向该描述符写音讯了. 战败时回来-1
int connect(int sockfd, struct sockaddr * serv_addr,int addrlen)
  • sockfd:socket再次来到的文本呈报符.
  • serv_addr:积存了劳务器端的连年信息.当中sin_add是服务端的地址
  • addrlen:serv_addr的长度
    connect函数是顾客端用来同服务端连接的.成功时再次回到0,sockfd是同服务端通信的公文陈诉符退步时重返-1

服务器端

socket-->bind-->listen-->accept-->(send ,recv)

客户端

socket-->connect-->(send ,recv)

telnet , nc

是一个用来远程调控的主次,不过我们一同能够用那个程序来调度大家的服务端程序的. 比如我们的服务器程序在监听8888端口,大家得以用来查阅服务端的情状.

telnet localhost 8888nc localhost 8888

server

#include <sys/socket.h>#include <sys/types.h>#include <netinet/in.h>#include <stdio.h>#include <stdlib.h>#include <unistd.h>int main(int argc, char* argv[]){    int listenport = 3333;    if(argc > 1)        listenport = atoi;    int sockfd = socket(AF_INET ,SOCK_STREAM, 0);    if(sockfd < 0 )        perror("socket");    struct sockaddr_in myaddr;    myaddr.sin_family = AF_INET;    myaddr.sin_port = htons(listenport);    myaddr.sin_addr.s_addr =  htonl(INADDR_ANY);    int res = bind(sockfd, (struct sockaddr*)&myaddr, sizeof(struct sockaddr_in));    if(res < 0 )        perror("bind");    // Set the "LINGER" timeout to zero, to close the listen socket    // immediately at program termination.    //struct linger linger_opt = { 1, 0 }; // Linger active, timeout 0    //setsockopt(sockfd, SOL_SOCKET, SO_LINGER, &linger_opt, sizeof(linger_opt));    res = listen(sockfd, 10);    int clientfd ;    while    {        struct sockaddr_in peeraddr;        socklen_t peeraddr_len;        clientfd = accept(sockfd, (struct sockaddr*)&peeraddr,&peeraddr_len);        printf("Connection from IP %d.%d.%d.%d, port %dn",                (ntohl(peeraddr.sin_addr.s_addr) >> 24) & 0xff, // High byte of address                (ntohl(peeraddr.sin_addr.s_addr) >> 16) & 0xff, // . . .                (ntohl(peeraddr.sin_addr.s_addr) >> 8) & 0xff,  // . . .                ntohl(peeraddr.sin_addr.s_addr) & 0xff,      // Low byte of addr                ntohs(peeraddr.sin_port));        char buffer[1024];        res = read(clientfd, buffer, 1023);        if (res < 0) {            perror("Read error");            exit;        }        buffer[res] = 0;        printf("Received %d bytes:n%sn", res, buffer);        close;    }    close;    return 0;}

client

#include <stdio.h>#include <string.h>#include <stdlib.h>#include <unistd.h>#include <sys/socket.h>#include <netinet/in.h>#include <netdb.h>int main(int argc, char *argv[]) {    // Create a socket    int s0 = socket(AF_INET, SOCK_STREAM, 0);    if (s0 < 0) {        perror("Cannot create a socket"); exit;    }    // Fill in the address of server    struct sockaddr_in peeraddr;    int peeraddr_len;    memset(&peeraddr, 0, sizeof);    char* peerHost = "127.0.0.1";    if (argc > 1)        peerHost = argv[1];    // Resolve the server address (convert from symbolic name to IP number)    struct hostent *host = gethostbyname;    if (host == NULL) {        perror("Cannot define host address"); exit;    }    peeraddr.sin_family = AF_INET;    short peerPort = 3333;    if (argc >= 3)        peerPort =  atoi;    peeraddr.sin_port = htons;    // Print a resolved address of server (the first IP of the host)    printf(        "peer addr = %d.%d.%d.%d, port %dn",        host->h_addr_list[0][0] & 0xff,        host->h_addr_list[0][1] & 0xff,        host->h_addr_list[0][2] & 0xff,        host->h_addr_list[0][3] & 0xff,         peerPort    );    // Write resolved IP address of a server to the address structure    memmove(&(peeraddr.sin_addr.s_addr), host->h_addr_list[0], 4);    // Connect to a remote server    int res = connect(s0, (struct sockaddr*) &peeraddr, sizeof);    if (res < 0) {        perror("Cannot connect"); exit;    }    printf("Connected. n");    char *c = "hhahhahhasa";    int size = strlen;    if(write(s0, c,size) <0){        perror("write ");        close;        return -1;    }    /*    char buffer[1024];    res = read(s0, buffer, 1024);    if (res < 0) {        perror("Read error");        exit;    }    printf("Received:n%s", buffer);    write(s0, "Thanks! Bye-bye...rn", 20);    */    close;    return 0;}

本文由编程发布,转载请注明来源:Socket 入门