C语言学习之Linux下TCP服务器与客户端的实现
客户端代码如下:#include
#include
#include
#include
#include
#include
#include
#include
服务器代码如下:
#include
#include
#include
#include
#include
#include
#include
#include
服务端:
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <stdio.h>
int main() {
int sockClient;
struct sockaddr_in addrSrv;
sockClient = socket(AF_INET,SOCK_DGRAM,0);
addrSrv.sin_addr.s_addr=inet_addr("127.0.0.1");
addrSrv.sin_family=AF_INET;
addrSrv.sin_port=htons(6000);
while(1)
{
sendto(sockClient,"Hello World",strlen("Hello World")+1,0,(struct sockaddr*)&addrSrv,sizeof(struct sockaddr));
sleep(2);
}
close(sockClient);
return 0;
}
客户端:#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/time.h>
#include <sys/select.h>
#include <sys/ioctl.h>
int main() {
int sockSrv;
struct sockaddr_in addrSrv;
int len;
char recvBuf;
scanf("%s",recvBuf);
struct sockaddr_in addrClient;
sockSrv = socket(AF_INET,SOCK_DGRAM,0);
addrSrv.sin_addr.s_addr = htonl(INADDR_ANY);
addrSrv.sin_family = AF_INET;
addrSrv.sin_port = htons(6000);
bind(sockSrv, (struct sockaddr *)&addrSrv, sizeof(struct sockaddr));
len = sizeof(struct sockaddr);
memset(recvBuf, 0, 100);
recvfrom(sockSrv, recvBuf, 100, 0, (struct sockaddr *)&addrClient,&len);
printf("客户端的IP地址:%s\r\n",inet_ntoa(addrClient.sin_addr));
printf("Client data is:%s\n",recvBuf);
close(sockSrv);
return 0;
}
页:
[1]