8.9 网络编程

编程入门 行业动态 更新时间:2024-10-27 01:35:58

8.9 <a href=https://www.elefans.com/category/jswz/34/1768814.html style=网络编程"/>

8.9 网络编程

 tcp服务器搭建:

#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#include<string.h>
#include<unistd.h>#define PORT 8888
#define IP "192.168.31.98"#define MSG(msg) do{\fprintf(stderr,"__%d__",__LINE__);\perror(msg);\
}while(0)int main(int argc, const char *argv[])
{int pp = socket(AF_INET, SOCK_STREAM ,0);if(pp<0){MSG("socket");return -1;}printf("create socket success\n");struct sockaddr_in sin;sin.sin_family = AF_INET;sin.sin_port = htons(PORT);sin.sin_addr.s_addr = inet_addr(IP);if(bind(pp,(struct sockaddr*)&sin,sizeof(sin))<0){MSG("bind");return -1;}printf("bind success\n");if(listen(pp,10)<0){MSG("listen");return -1;}printf("listen success\n");struct sockaddr_in cin;socklen_t addrlen = sizeof(cin);int newfd = accept(pp,(struct sockaddr *)&cin,&addrlen);if(newfd<0){MSG("accept");return -1;}printf("%s : %d newfd = %d\n",inet_ntoa(cin.sin_addr),ntohs(cin.sin_port),newfd);char buf[128] = "";ssize_t res = 0;while(1){bzero(buf,sizeof(buf));res = recv(newfd,buf,sizeof(buf),0);if(res<0){MSG("recv");return -1;}else if(res == 0){printf("%s  %d  newfd = %d客户端退出\n",inet_ntoa(cin.sin_addr),ntohs(cin.sin_port),newfd);break;}printf("%s %d  newfd = %d :  %s\n",inet_ntoa(cin.sin_addr),ntohs(cin.sin_port),newfd,buf);}close(pp);close(newfd);return 0;
}

更多推荐

8.9 网络编程

本文发布于:2023-06-29 22:56:42,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/951995.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:网络编程

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!