每一天都值得去热爱!
udp客户端代码
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include<WS2tcpip.h>
#include <windows.h>
#pragma comment(lib,'ws2_32.lib')
int main(){
WSADATA data;
WORD version = MAKEWORD(2, 2);
WSAStartup(version, &data);
int sockets=0;
sockets=socket(AF_INET,SOCK_DGRAM,0);
if(sockets<0){
printf('socket connect failed');
return -1;
}
printf('socket initialize success ');
while(1){
int tolen=0;
int ret=0;
char buf[1024]={0};
gets(buf);
struct sockaddr_in client;
memset(&client, 0, sizeof(client));
client.sin_family = AF_INET;
client.sin_port = htons(8888);
client.sin_addr.s_addr = inet_addr('192.168.132.1');
ret=sendto(sockets,(char *)&buf, sizeof(buf),0,(struct sockaddr *) &client, sizeof(client));
if(ret<0){
printf('sendto failed');
return -1;
}
printf('sendto success ');
ret=recvfrom(sockets,(char *)&buf, sizeof(buf),0,(struct sockaddr *) &client,(socklen_t *)&client);
if(ret<0){
printf('recvfrom failed');
return -1;
}
printf('IP=%s,port=%d ',inet_ntoa(client.sin_addr),ntohs(client.sin_port));
printf('recvfrom success ');
printf('receive: %s ',buf);
closesocket(sockets);
WSACleanup();
}
}
服务器端代码
#include <stdio.h>
#include <stdlib.h>#include <time.h>
#include <string.h>
#include<WS2tcpip.h>
#include <windows.h>
#pragma comment(lib,'ws2_32.lib')
int main(){
WSADATA data;
WORD version = MAKEWORD(2, 2);
WSAStartup(version, &data);
int sockets=0;
sockets=socket(AF_INET,SOCK_DGRAM,0);
if(sockets<0){
printf('socket connect failed');
return -1;
}
printf('socket initialize success ');
int ret=0;
struct sockaddr_in server;
memset(&server, 0, sizeof(server));
server.sin_family = AF_INET;
server.sin_port = htons(8888);
server.sin_addr.s_addr = inet_addr('192.168.132.1');
ret=bind(sockets,(struct sockaddr *)&server,sizeof(server));
if(ret<0){
printf('bind failed');
return -1;
}
printf('bind success ');
while(1){
int addrlen=0;
char buf[1024]={0};
struct sockaddr_in clientaddr={0};
addrlen=sizeof(clientaddr);
ret=recvfrom(sockets,(char *)&buf, sizeof(buf),0,(struct sockaddr *) &clientaddr,(socklen_t *)&addrlen);
if(ret<0){
printf('recvfrom failed');
return -1;
}
printf('IP=%s,port=%d ',inet_ntoa(clientaddr.sin_addr),ntohs(clientaddr.sin_port));
printf('recvfrom success ');
printf('receive: %s ',buf);
memset(buf,0,sizeof(buf));
gets(buf);
ret=sendto(sockets,(char *)&buf, sizeof(buf),0,(struct sockaddr *) &server, sizeof(server));
if(ret<0){
printf('sendto failed');
return -1;
}
printf('sendto success ');
closesocket(sockets);
WSACleanup();
}
}
运行效果: