1 创建socket,返回一个文件描述符cfd---socket();
2 连接服务端---connect();
3 while(1)
{
//发送数据 write
//接收数据 read
}
4 close(cfd);
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<sys/types.h>
#include<unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include<arpa/inet.h>
int main()
{int cfd=socket(AF_INET,SOCK_STREAM,0);if(cfd<0){perror("socket error");return -1;}struct sockaddr_in addr;bzero(&addr,sizeof(addr));addr. sin_family=AF_INET;addr.sin_port=htons(9999);
//点分十进制变网络字节序inet_pton(AF_INET,"192.168.230.130",&addr.sin_addr.s_addr);//服务端IP地址printf("[%x]\n",addr.sin_addr.s_addr);//打印大端字节序的网络字节序//int connect(int sockfd, const struct sockaddr *addr,// socklen_t addrlen);int ret= connect(cfd,(struct sockaddr*)&addr,sizeof(addr));if(ret<0){perror("connect error");return -1;} int n;char buf[64];while(1){memset(buf,0x00,sizeof(buf));n=read(STDIN_FILENO,buf,sizeof(buf));//从标准输入读write(cfd,buf,strlen(buf));//发送给服务端memset(buf,0x00,sizeof(buf));n=read(cfd,buf,sizeof(buf));//读服务端发的信息if(n<0||n==0){printf("read error or serve close\n");break;}printf("n==[%d],buf==[%s]\n",n,buf);}close(cfd);return 0;
}
结果:
服务端结果:
通过 netstat -anp 命令查看: