红联Linux门户
Linux帮助

UDP方式广播通讯,socket编程,出现段错误

发布时间:2011-03-08 00:51:40来源:红联作者:hsnowirp
服务器端源代码:[code]
#include

#include

#include

#include

#include

#include

#include

#include



int main(int argc, char **argv)

{

struct sockaddr_in s_addr;

struct sockaddr_in c_addr;

int sock;

socklen_t addr_len;

int len;

char buff[128];



/* 创建socket */

if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) == -1) {

perror("socket");

exit(errno);

} else

printf("create socket.\n\r");

memset(&s_addr, 0, sizeof(struct sockaddr_in));



/* 设置IP和端口 */

s_addr.sin_family = AF_INET;

s_addr.sin_port = htons(7838);

s_addr.sin_addr.s_addr = INADDR_ANY;



/* 绑定IP和端口 */

if ((bind(sock, (struct sockaddr *) &s_addr, sizeof(s_addr))) == -1) {

perror("bind");

exit(errno);

} else

printf("bind address to socket.\n\r");



/* 循环接收数据 */

addr_len = sizeof(c_addr);

while (1) {
bzero( buff, sizeof(buff) );

len = recvfrom(sock, buff, sizeof(buff) - 1, 0,

(struct sockaddr *) &c_addr, &addr_len);

if (len < 0) {

perror("recvfrom");

exit(errno);

}

buff[len] = '\0';

printf("recevied from % : %d : %s\n\r",

inet_ntoa(c_addr.sin_addr), ntohs(c_addr.sin_port), buff);

}

return 0;

}[/code]客户端源代码:[code]
#include

#include

#include

#include

#include

#include

#include

#include



int main(int argc, char **argv)

{

struct sockaddr_in s_addr;

int sock;

int addr_len;

int len;

char buff[128];

int yes;



/* 创建socket */

if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) == -1) {

perror("socket");

exit(errno);

} else

printf("create socket.\n\r");



/* 设置广播 */

yes = 1;

setsockopt(sock, SOL_SOCKET, SO_BROADCAST, &yes, sizeof(yes));



/* 设置IP和端口 */

s_addr.sin_family = AF_INET;

s_addr.sin_port = htons(7838);

if (argv[1])

s_addr.sin_addr.s_addr = inet_addr(argv[1]);

else {

printf("must \n");

exit(0);

}


/* 发送UDP消息 */

addr_len = sizeof(s_addr);

strcpy(buff, "hello i'm here");

len = sendto(sock, buff, strlen(buff), 0,

(struct sockaddr *) &s_addr, addr_len);

if (len < 0) {

printf("\n\rsend error.\n\r");

return 3;

}

printf("send success.\n\r");

return 0;

}


[/code]编译:gcc ser.c -o ser
gcc cli.c -o cli

一个终端运行:./ser 192.168.0.100 7838
显示:create socket.
bind address to socket.

另一个终端运行:./cli 192.168.0.255 7838
显示:create socket.
send success.
此时服务器终端显示:段错误
文章评论

共有 3 条评论

  1. qinshunfu 于 2012-04-10 17:00:16发表:

    执行过程没有必要加端口号

  2. 于 2012-03-27 11:56:30发表:

    服务器端的printf()语句有误,参数不匹配, %s %d %s打印三个参数

  3. iuears 于 2011-03-08 08:40:08发表:

    不懂,帮顶