1.定义一个结构(host_sockaddr_in) ,并把通讯的另一端的信息填充
2.定义一个结构(local_sockaddr_in),并把本机的信息填充
3.创建一个Socket
4.绑定本机端口,作为本机监听接收端口
5.根据实际需要,设置非阻塞方式接收数据
6.在用完Socket后,关闭Socket : close(skt)
program list:
#include<stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <sys/types.h>
#include <net/if.h>
#include <ifaddrs.h>
#include<unistd.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<termios.h>
#include<errno.h>
static inthost_port =8888; //服务器上的端口
static int local_port = 9999; //本机接收端口
static char * host_ip ="192.168.123.234";
static struct sockaddr_in local_sockaddr_in ;//local
static struct sockaddr_in host_sockaddr_in; //server
int Create_Socket()
{
int skt;
int fd;
int port =local_port;
char *local_ip=getIPv4(); //提取本机IP,getIPv4()请参考上一遍文章
printf("* Create aSocket......");
// 1. Initialize socket host_sockaddr_instructure for Internet Protocols
// bzero(&host_sockaddr_in,sizeof(host_sockaddr_in)); //empty data structure
memset (&host_sockaddr_in, 0 ,sizeof(host_sockaddr_in) ); //empty datastructure
host_sockaddr_in.sin_family = AF_INET;
host_sockaddr_in.sin_addr.s_addr =inet_addr(host_ip);
host_sockaddr_in.sin_port =htons(host_port);
// 2. Initialize socketlocal_sockaddr_in structure for Internet Protocols
//bzero(&local_sockaddr_in,sizeof(local_sockaddr_in)); // empty data structure
memset (&local_sockaddr_in, 0 ,sizeof(local_sockaddr_in) );
local_sockaddr_in.sin_family = AF_INET;
local_sockaddr_in.sin_addr.s_addr =inet_addr(local_ip);
local_sockaddr_in.sin_port =htons(local_port);
// 3. Create a UDPsocket
skt = socket(AF_INET,SOCK_DGRAM, 0);
if (-1==skt)
{//printf("Create Socket : failure!\n");
printf("[Failure]\n\n");
return-1;
}
else
//printf("Create Socket : success! & socket=%d\n",skt);
printf("[OK]\n\n");
// 4. bind to the port
printf("* Bind the Port to theSocket......");
fd= bind(skt, (struct sockaddr*)&local_sockaddr_in,sizeof(local_sockaddr_in));
if(-1==fd)
{//printf("Port binding :failure!\n");
printf("[Failure]\n\n");
return -1;
}
else
{ //printf("Port binding:success! & Port =%d\n",port);
printf("[OK]\n");
printf("Local Port =%d\n\n",port);
}
// 5. Set Socket tonon-blocking
save_file_flags|= O_NONBLOCK;
fcntl(skt,F_SETFL,save_file_flags); //Set Socketto non-blocking
return skt;
}
//UDP Send
void UDP_TX(char *buf )
{
sendto(socket_descriptor,\
buf, sizeof(buf),\
0, (struct sockaddr *)&host_sockaddr_in, \
sizeof(host_sockaddr_in));
}
//UDP Receive
void * UDP_RX()
{ static char buf[46];
int len = sizeof(local_sockaddr_in);
memset(buf,0,46);
int ret=recvfrom(socket_descriptor, buf, sizeof(buf), 0,\
(struct sockaddr *)&local_sockaddr_in, \
(socklen_t*)&len);
printf("recv=%d buf=%s\n",ret,buf);
return buf;
}
参考《GNU/Linux编程指南.第二版》