C语言 UDP socket 简单客户端 编程,急
发布网友
发布时间:2022-04-27 07:06
我来回答
共2个回答
热心网友
时间:2022-06-28 05:59
提一下,你那个地址不好用,换成了127.0.0.1,端口可以用,完全按照要求写的,编译没错误,调试通过:
gcc server.c -o server
gcc client.c -o client
打开2个控制台:一个运行 ./server 另一个运行 ./client
server.c:
========================================
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <errno.h>
#define BUFFERSIZE 1024
typedef struct sockaddr SA;
int main(void)
{
char buf[BUFFERSIZE];
struct sockaddr_in addr_s;
struct sockaddr_in addr_c;
int sockfd;
socklen_t length;
int i;
if((sockfd = socket(AF_INET,SOCK_DGRAM,0)) == -1)
{
perror("socket fail");
return -1;
}
memset(&addr_s,0,sizeof(addr_s));
addr_s.sin_family = AF_INET;
addr_s.sin_addr.s_addr = inet_addr("127.0.0.1");
addr_s.sin_port = htons(31180);
if(bind(sockfd,(SA *)&addr_s,sizeof(addr_s)) == -1)
{
perror("bind fail");
return -1;
}
length = sizeof(addr_c);
memset(buf,'\0',sizeof(buf));
if(recvfrom(sockfd,buf,sizeof(buf),0
,(SA *)&addr_c,&length) == -1)
{
perror("recvfrom fail");
}
printf("recvfrom client:%s\n",buf);
sendto(sockfd,buf,sizeof(buf),0,(SA *)&addr_c,sizeof(addr_c));
close(sockfd);
}
====================================
client.c:
====================================
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <errno.h>
#define BUFFERSIZE 1024
typedef struct sockaddr SA;
int main(void)
{
int sockfd;
char buf[BUFFERSIZE];
struct sockaddr_in addr_s;
if((sockfd = socket(AF_INET,SOCK_DGRAM,0)) == -1)
{
perror("socket fail");
return -1;
}
memset(&addr_s,0,sizeof(addr_s));
addr_s.sin_family = AF_INET;
addr_s.sin_addr.s_addr = inet_addr("127.0.0.1");
addr_s.sin_port = htons(31180);
memset(buf,'\0',sizeof(buf));
sprintf(buf,"abcde");
if(sendto(sockfd,buf,sizeof(buf)
,0,(SA *)&addr_s,sizeof(addr_s)) < 0)
{
perror("sendto fail");
}
memset(buf,'\0',sizeof(buf));
recvfrom(sockfd,buf,sizeof(buf),0,NULL,NULL);
printf("recvfrom server:%s\n",buf);
close(sockfd);
}追问谢了,能稍微改一下换成输入一段字符而不是事先设好的字符么。
追答client.c:
====================================
#include
#include
#include
#include
#include
#include
#include
#define BUFFERSIZE 1024
typedef struct sockaddr SA;
int main(void)
{
int sockfd;
char buf[BUFFERSIZE];
struct sockaddr_in addr_s;
if((sockfd = socket(AF_INET,SOCK_DGRAM,0)) == -1)
{
perror("socket fail");
return -1;
}
memset(&addr_s,0,sizeof(addr_s));
addr_s.sin_family = AF_INET;
addr_s.sin_addr.s_addr = inet_addr("127.0.0.1");
addr_s.sin_port = htons(31180);
memset(buf,'\0',sizeof(buf));
//这里加2句,去掉原来的那一句就可以了
printf("input the message to send:\n");
scanf("%s",buf);
if(sendto(sockfd,buf,sizeof(buf)
,0,(SA *)&addr_s,sizeof(addr_s)) < 0)
{
perror("sendto fail");
}
memset(buf,'\0',sizeof(buf));
recvfrom(sockfd,buf,sizeof(buf),0,NULL,NULL);
printf("recvfrom server:%s\n",buf);
close(sockfd);
}
热心网友
时间:2022-06-28 06:00
找我吧,这个简单追问可以啊,程序...........