host.c:
#include
#include
#include
#include
#include
#include
#include
#include
#include
void main(int argc,char **argv[])
{
struct sockaddr_in add;
int fd, fd1, i;
int len;
char msg[100] = "i am host\n";
char buf[100];
int yes;
fd = socket(AF_INET, SOCK_DGRAM, 0);
len = sizeof(add);
bzero(&add, sizeof(add));
add.sin_port = htons(5000);
add.sin_family = AF_INET;
add.sin_addr.s_addr = htonl(INADDR_ANY);
bind(fd, (struct sockaddr*)&add, sizeof(add));
recvfrom(fd, buf, 100, 0, (struct sockaddr *)&add, &len);
printf("msg recv:%s\n", buf);
}
cli.c:
#include
#include
#include
#include
#include
#include
#include
#include
#include
void main(int argc,char **argv[])
{
struct sockaddr_in add;
int fd, fd1, i;
int len;
int yes = 1;
char msg[100] = "i am cli\n";
char buf[100];
fd = socket(AF_INET, SOCK_DGRAM, 0);
setsockopt(fd, SOL_SOCKET, SO_BROADCAST, &yes, sizeof(yes));
bzero(&add, sizeof(add));
add.sin_port = htons(5000);
add.sin_family = AF_INET;
add.sin_addr.s_addr = inet_addr("10.144.15.255");
sendto(fd,msg, strlen(msg), 0, (struct sockaddr *)&add, sizeof(add));
}
makefile:
LIB = -lsocket -lnsl
all : clean host cli
.PHONY : all
clean :
-rm *.o core host cli
host : host.o
cc -o host host.o $(LIB)
host.o : host.c
cc -c host.c $(LIB)
cli : cli.o
cc -o cli cli.o $(LIB)
cli.o : cli.c
cc -c cli.c $(LIB)
与udp程序相比,只是多了红色部分代码。
阅读(518) | 评论(0) | 转发(0) |