首页 > 代码库 > linux下socket编程

linux下socket编程

1.创建socket

int listenfd;listenfd = socket(AF_INET, SOCK_STREAM, 0); // 流式套接字if(listenfd < 0){  perror("socket");  exit(1);    }

 

2.绑定bind

struct sockaddr_in serv_addr, cli_addr;bzero(&serv_addr, sizeof(serv_addr));  sin.sin_family = AF_INET;sin.sin_port = htons(6363); // 端口号sin.sin_addr.s_addr = htonl(INADDR_ANY); // IP地址// 避免绑定不成功int on = 1;setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &on , sizeof(int));if( bind(listenfd,(struct sockaddr *)&serv_addr, sizeof(serv_addr)) == -1){    perror("bind failed.\n");    exit(1);} 

 

3.监听listen

if(listen(listenfd, n) == -1) // n代表监听的数量{    perror("listen failed\n");    exit(1);}

 

4.accept

int clientfd;// struct sockaddr_in cli_addr;int len = sizeof(struct sockaddr);clientfd= accept(serverfd, (struct sockaddr*)&cli_addr, &len);if(clientfd == -1){    perror("accept failed\n");    exit(1);}else    printf("accept succeed\n");

 

5.连接connect

int sockfd;struct sockaddr_in serv_addr;host = gethostbyname("127.0.0.1");sockfd = socket(AF_INET, SOCK_STREAM, 0);bzero(&serv_addr, sizeof(struct sockaddr));serv_addr.sin_family = AF_INET;serv_addr.sin_port = htons(port); // port端口号serv_addr.sin_addr = *((struct in_addr *)host->h_addr);if(connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(struct sockaddr)) == -1){    printf("connect failed\n");    exit(1);}else    printf("connect succeed \n");

 

6.发送数据send // tcp

send(sockfd, buf, strlen(buf), 0);

 

7.接收数据recv // tcp

int recvNum;char buf[BUF_SIZE]; // define BUF_SIZE 1024if((recvNum = recv(sockfd, buf, BUF_SIZE, 0)) > 0){    printf("recv: %s\n", buf);}else if(recvNum == -1){    perror("recv -1");    exit(1);}

 

8.创建线程

1.添加头文件#include <pthread.h>2.编译时添加参数gcc -g xxx.c -o xxx -pthread3.pthread_t pid;int sockfd;pthread_create(&pid, NULL, (void*)recv_data,(void*)&sockfd);其中:void *recv_data(void *fd){  int sockfd = *((int *)fd );  ...    while(1)    {        recv(...);        }  }

 

 

linux下socket编程