//udp接收消息
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h> #include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h> int main(int arg, char * args[])
{
if (arg < )
{
printf("please print two param!\n");
return -;
}
int port = atoi(args[]);
//create socket
int st = socket(AF_INET, SOCK_DGRAM, );
if (st == -)
{
printf("create socket failed ! error message :%s\n", strerror(errno));
return -;
}
//UDP广播必须设置socket属性
/*
int on = 1;
if (setsockopt(st, SOL_SOCKET, SO_BROADCAST, &on, sizeof(on)) == -1)
{
printf("setsockopt failed ! error message :%s\n", strerror(errno));
return -1;
}
*/
struct sockaddr_in addr;
memset(&addr, , sizeof(addr));
//设置结构sockaddr_in类型是TCP/IP
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = inet_addr(args[]);
char buf[] = { };
while ()
{
//read
read(STDIN_FILENO, buf, sizeof(buf));
if (sendto(st, buf, strlen(buf), , (struct sockaddr *) &addr,
sizeof(addr)) == -)
{
printf("sendto failed ! error message :%s\n", strerror(errno));
break;
}
memset(buf,,sizeof(buf));
}
close(st);
return ;
}
//udp接收消息
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h> #include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h> int main(int arg, char * args[])
{
if(arg<)
{
printf("please print one param !\n");
return -;
}
int st=socket(AF_INET,SOCK_DGRAM,);
if(st==-)
{
printf("open socket failed ! error message : %s\n",strerror(errno));
return -;
}
int port=atoi(args[]);
//defien ip address strcut
struct sockaddr_in addr;
//define addr type
addr.sin_family=AF_INET;
addr.sin_port=htons(port);
addr.sin_addr.s_addr=htonl(INADDR_ANY);
//bind port
if(bind(st,(struct sockaddr *)&addr,sizeof(addr))==-)
{
printf("bind IP failed ! error message : %s\n",strerror(errno));
goto END;
}
char buf[]={};
struct sockaddr_in client_addr;
socklen_t addrlen=sizeof(client_addr);
while()
{
memset(&client_addr,,sizeof(client_addr));
if(recvfrom(st,buf,sizeof(buf),,(struct sockaddr *)&client_addr,&addrlen)==-)
{
printf("recvfrom failed ! error message : %s\n",strerror(errno));
goto END;
}else
{
printf("from %s:%s",inet_ntoa(client_addr.sin_addr),buf);
}
memset(buf,,sizeof(buf));
}
END:close(st);
return ;
}
.SUFFIXES:.c .o
CC=gcc
SRCS1=udpsend.c
SRCS2=udprecv.c
OBJS1=$(SRCS1:.c=.o)
OBJS2=$(SRCS2:.c=.o)
EXEC1=msend
EXEC2=mrecv start:$(OBJS1) $(OBJS2)
$(CC) -o $(EXEC1) $(OBJS1)
$(CC) -o $(EXEC2) $(OBJS2)
@echo "-------ok-----------"
.c.o:
$(CC) -Wall -g -o $@ -c $<
clean:
rm -f $(OBJS1)
rm -f $(EXEC1)
rm -f $(OBJS2)
rm -f $(EXEC2)