赞
踩
- #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 ERR_MSG(msg)do{\
- fprintf(stderr,"line:__%d__",__LINE__);\
- perror(msg);\
- }while(0)
-
- #define PORT 9999 //1024~49151
- #define IP "192.168.8.57"//ifconfig查看
-
- int main(int argc, const char *argv[])
- {
- //创建流式套接字 --> TCP
- int sfd = socket(AF_INET,SOCK_STREAM,0);
- if(sfd < 0){
- ERR_MSG("socket");
- return -1;
- }
- printf("sfd = %d\n",sfd);
-
-
- //填充地址信息结构体,真实的地址信息结构体在man 7 ip
- //AF_INET --> man 7 ip
- struct sockaddr_in sin;
- sin.sin_family = AF_INET; //必须填AF_INET;
- sin.sin_port = htons(PORT); //1024~49151,网络字节序
- sin.sin_addr.s_addr = inet_addr(IP); //本机IP,ifconfig查看
-
- //功能:将IP地址和端口号绑定到指定套接字中;
- if(bind(sfd,(struct sockaddr *)&sin,sizeof(sin)) < 0){
- ERR_MSG("bind");
- return -1;
- }
- printf("bind success __%d__\n",__LINE__);
-
- //功能:将套接字设置为被动监听状态,只负责监听是否有客户端连接成功;
- if(listen(sfd,10) < 0){
- ERR_MSG("listen");
- return -1;
- }
- printf("listen success\n");
-
- struct sockaddr_in cin; //存储客户端的地址信息
- socklen_t addrlen = sizeof(cin);
- int newfd = 0;
-
- //功能:阻塞函数,阻塞等待客户端连接成功
- //当客户端连接成功后,会从已完成连接的队列头中获取一个客户端信息,
- //并生成一个新的文件描述符;
- //注意:新生成的文件描述符才是用于通信的文件描述符;
- newfd = accept(sfd,(struct sockaddr *)&cin,&addrlen);
- if(newfd < 0){
- ERR_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){
- ERR_MSG("recv");
- return -1;
- }
- else if(0 == res){
- 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);
-
- //发送
- printf("请输入发送的消息>>>>");
- bzero(buf,sizeof(buf));
- fgets(buf,sizeof(buf),stdin);
- res=send(newfd,buf,sizeof(buf),0);
- if(-1==res){
- ERR_MSG("send");
- break;
- }
- }
-
- close(newfd);
- close(sfd);
- return 0;
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。