日期:2014-05-16  浏览次数:20684 次

linux下UDP通信,代码如下,在同一台主机上运行程序,每次运行Client一直连不上Server,求各位大哥指点!!!
[code=C/C++][/code]
Server服务器端

#include <sys/types.h>
#include <sys/socket.h>
//#include <linux/in.h>
#include <string.h>
#include <stdio.h>
#include <netinet/in.h>
#include <stdlib.h>

#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 receive\n");
n = recvfrom(s, buff, BUFF_LEN, 0, client, &len);
printf("have received\n");
printf("message is :s%", buff);
sendto(s, buff, n, 0, client, len);
printf("echo\n");
}
}

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 <sys/types.h>
#include <sys/socket.h>
#include <linux/in.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#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 6\n");
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++] = '\0';
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 finished\n");

close(s);
return 0;
}


代码如上,运行Server和Client后,Server服务器端运行到“printf("ready to receive\n")”,就没有往下运行了。
Client端运行后,报connect error:permission denied。 这是怎么回事啊?求各位大侠指点!!!

------解决方案--------------------
友情帮顶..
------解决方案--------------------
怎么报permission denied错误,在那里运行的?
------解决方案--------------------
UDP通信,你用的是sendto和recvfrom。那么你不能使用connect。。


不用connect。。直接sendto就行。。。
------