实现简单UDP客户端和服务器端
服务器端:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
typedef struct sockaddr sockaddr;
typedef struct sockaddr_in sockaddr_in;
int main(int argc,char* argv[]) {
int sock = socket(AF_INET,SOCK_DGRAM,0);
if (sock<0)
{
perror("socket");
return 2;
}
struct sockaddr_in local;
local.sin_family=AF_INET;
local.sin_port=htons(atoi(argv[1]));
local.sin_addr.s_addr=htonl(INADDR_ANY);
if (bind(sock,(struct sockaddr*)&local,sizeof(local))<0)
{
perror("bind");
return 3;
}
char buf[1024];
struct sockaddr_in client;
while(1)
{
socklen_t len= sizeof(client);
ssize_t s=recvfrom(sock,buf,sizeof(buf)-1,0,(struct sockaddr*)&client,&len);
if(s>0)
{
buf[s]=0;
printf("[%s:%d]: %s\n",inet_ntoa(client.sin_addr),ntohs(client.sin_port),buf);
sendto(sock,buf,strlen(buf),0,(struct sockaddr*)&client,sizeof(client));
}
}
return 0;
}
客户端
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
typedef struct sockaddr sockaddr;
typedef struct sockaddr_in sockaddr_in;
int main(int argc,char* argv[]) {
int sock=socket(AF_INET,SOCK_DGRAM,0);
if (sock<0) {
perror("socket");
return 2;
}
struct sockaddr_in server;
server.sin_family=AF_INET;
server.sin_port=htons(atoi(argv[2]));
server.sin_addr.s_addr=inet_addr(argv[1]);
char buff[1024];
struct sockaddr_in peer;
while(1)
{
socklen_t len =sizeof(peer);
printf("please enter: ");
fflush(stdout);
ssize_t s=read(0,buff,sizeof(buff)-1);
if(s>0)
{
buff[s-1]=0;
sendto(sock,buff,strlen(buff),0,(struct sockaddr*)&server,sizeof(server));
ssize_t _s=recvfrom(sock,buff,sizeof(buff)-1,0,(struct sockaddr*)&peer,&len);
if (_s>0) {
buff[_s]=0;
printf("server echo %s\n",buff);
}
}
}
return 0;
}
测试
1.运行服务器
2.检查端口
3.运行客户端
4.查看服务器端