当前位置: 技术问答>linux和unix
UDP socket program
来源: 互联网 发布时间:2016-03-18
本文导语: 写了个简单的udp server and client的code server运行后 一直没有反应 client 运行后 直接打出read failed: Connection refused 查了半天 也不知道为什么 请高人指点迷津 server code %%%%%%%%%%%%%%%%% #include #include ...
写了个简单的udp server and client的code
server运行后 一直没有反应
client 运行后 直接打出read failed: Connection refused
查了半天 也不知道为什么 请高人指点迷津
server code
%%%%%%%%%%%%%%%%%
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define BUFLEN 1024
#define PORT 5090
int main(void)
{
struct sockaddr_in cli;
struct sockaddr_in ser;
int s, i, j, m, pid, fd1[2], fd2[2], n, c, slen=sizeof(ser);
int clen=sizeof(cli);
char buf[BUFLEN];
char pw[BUFLEN];
char ph[BUFLEN];
char cm[BUFLEN];
char pip[BUFLEN];
char mystruct[BUFLEN];
if ((s=socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP))==-1)
{
perror("cannot set up socket");
exit(1);
}
memset((char *) &ser, 0, sizeof(ser));
ser.sin_family = AF_INET;
ser.sin_port = htons((uint16_t)PORT);
ser.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(s, (struct sockaddr *)&ser, sizeof(ser))==-1)
{
perror("cannot bind");
exit(1);
}
while (1)
{
perror("inside while loop");//debug
if (recvfrom(s, buf, sizeof(buf), 0, (struct sockaddr*)&cli, &clen) h_addr,(char*)&cli.sin_addr.s_addr,myhost->h_length);
// memcpy(&sin.sin_addr.s_addr,myhost->h_addr,myhost->h_length);
else if ((cli.sin_addr.s_addr=inet_addr(argv[1]))==-1)
{
perror("cannot get host name");
exit(1);
}
bzero((char *) &cli, sizeof(cli));
cli.sin_family = AF_INET;
cli.sin_port = htons((uint16_t)p);
s=socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (s
server运行后 一直没有反应
client 运行后 直接打出read failed: Connection refused
查了半天 也不知道为什么 请高人指点迷津
server code
%%%%%%%%%%%%%%%%%
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define BUFLEN 1024
#define PORT 5090
int main(void)
{
struct sockaddr_in cli;
struct sockaddr_in ser;
int s, i, j, m, pid, fd1[2], fd2[2], n, c, slen=sizeof(ser);
int clen=sizeof(cli);
char buf[BUFLEN];
char pw[BUFLEN];
char ph[BUFLEN];
char cm[BUFLEN];
char pip[BUFLEN];
char mystruct[BUFLEN];
if ((s=socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP))==-1)
{
perror("cannot set up socket");
exit(1);
}
memset((char *) &ser, 0, sizeof(ser));
ser.sin_family = AF_INET;
ser.sin_port = htons((uint16_t)PORT);
ser.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(s, (struct sockaddr *)&ser, sizeof(ser))==-1)
{
perror("cannot bind");
exit(1);
}
while (1)
{
perror("inside while loop");//debug
if (recvfrom(s, buf, sizeof(buf), 0, (struct sockaddr*)&cli, &clen) h_addr,(char*)&cli.sin_addr.s_addr,myhost->h_length);
// memcpy(&sin.sin_addr.s_addr,myhost->h_addr,myhost->h_length);
else if ((cli.sin_addr.s_addr=inet_addr(argv[1]))==-1)
{
perror("cannot get host name");
exit(1);
}
bzero((char *) &cli, sizeof(cli));
cli.sin_family = AF_INET;
cli.sin_port = htons((uint16_t)p);
s=socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (s