当前位置: 技术问答>linux和unix
linux下UDP通信,代码如下,在同一台主机上运行程序,每次运行Client一直连不上Server,求各位大哥指点!!!
来源: 互联网 发布时间:2016-12-12
本文导语: Server服务器端 #include #include //#include #include #include #include #include #define PORT_SERV 8889 #define BUFF_LEN 1024 static void UDP_server_process(int s, struct sockaddr *client, socklen_t clilen) { int n; socklen_t len; char buff[BUFF_LEN]; while(...
Server服务器端
#include
#include
//#include
#include
#include
#include
#include
#define PORT_SERV 8889
#define BUFF_LEN 1024
static void UDP_server_process(int s, struct sockaddr *client, socklen_t clilen)
{
int n;
socklen_t len;
char buff[BUFF_LEN];
while(1)
{
len = clilen;
printf("ready to receiven");
n = recvfrom(s, buff, BUFF_LEN, 0, client, &len);
printf("have receivedn");
printf("message is :s%", buff);
sendto(s, buff, n, 0, client, len);
printf("echon");
}
}
int main(int argc, char **argv)
{
int s;
struct sockaddr_in addr_serv, addr_clie;
s = socket(AF_INET, SOCK_DGRAM, 0);//creat a socket
bzero(&addr_serv, sizeof(addr_serv));
addr_serv.sin_family = AF_INET;
addr_serv.sin_addr.s_addr = htonl(INADDR_ANY);
addr_serv.sin_port = htons(PORT_SERV);
if(bind(s, (struct sockaddr *)&addr_serv, sizeof(addr_serv)) == -1)
{
perror("bind error");
exit(1);
}
UDP_server_process(s, (struct sockaddr *)&addr_clie, sizeof(addr_clie));
return 0;
}
Client客户端
#include
#include
#include
#include
#include
#include
#include
#define PORT_SERV 8889
#define BUFF_LEN 1024
#define SERV_IP "152.156.245.255"
static void UDP_client_process(FILE *fp, int s, struct sockaddr *to, socklen_t tolen)
{
char SendBuff[BUFF_LEN];
int n;
int len = sizeof(*to);
printf("ok 6n");
if(connect(s, (struct sockaddr *)to, tolen) == -1)
{
perror("connect error");
exit(1);
}
printf("please input message!");
printf("ok 7 n");
while(fgets(SendBuff, BUFF_LEN, fp) != NULL)
{
printf("this is SendBuff:%s", SendBuff);
write(s, SendBuff, strlen(SendBuff));//发送
n = read(s, SendBuff, BUFF_LEN);//接收
if(n == -1)
{
perror("read error");
exit(1);
}
SendBuff[n++] = '';
fputs(SendBuff, stdout);
}
}
int main(int argc, char **argv)
{
int s;
struct sockaddr_in addr_serv, addr_clie;
char *msg;
if(argc != 3)
{
printf("parameter is error!");
printf("format:ip port");
return -1;
}
printf("ok 1;n");
s = socket(AF_INET, SOCK_DGRAM, 0);
bzero(&addr_serv, sizeof(addr_serv));
addr_serv.sin_family = AF_INET;
addr_serv.sin_addr.s_addr = inet_addr(argv[1]);
addr_serv.sin_port = htons(atoi(argv[2]));
UDP_client_process(stdin, s, (struct sockaddr*)&addr_serv, sizeof(addr_serv));
printf("ok it's finishedn");
close(s);
return 0;
}
代码如上,运行Server和Client后,Server服务器端运行到“printf("ready to receiven")”,就没有往下运行了。
Client端运行后,报connect error:permission denied。 这是怎么回事啊?求各位大侠指点!!!
|
UDP通信,你用的是sendto和recvfrom。那么你不能使用connect。。
不用connect。。直接sendto就行。。。
不用connect。。直接sendto就行。。。
|
怎么报permission denied错误,在那里运行的?
|
你用root用户运行一下就可以了,我做的时候碰到这个问题!
|
友情帮顶..