首页 > 代码库 > 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编程
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。