udp通信源代码如下
udp.h
#ifndef UDP_H_
#define UDP_H_
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#define SERVER 1
#define CLIENT 0
typedef struct _net_udp
{
int fd;
struct sockaddr_in addr;
int isServerClinet;
}NET_UDP;
NET_UDP *udpCreate(char IP[], int port, int isServerClient);
int udpSend(NET_UDP *pUdp, unsigned char *pData, int dataLen, int sendLenOneTime);
int udpRecv(NET_UDP *pUdp, unsigned char *pData, int recvLen);
int udpClose(NET_UDP *pUdp);
#endif
udp.c
#include "udp.h"
NET_UDP *udpCreate(char IP[], int port, int isSerClint)
{
NET_UDP *pUdp = NULL;
pUdp = (NET_UDP *)malloc(sizeof(NET_UDP));
if(NULL == pUdp)
{
printf("%s, pUdp malloc failed.\n", __FUNCTION__);
return NULL;
}
struct sockaddr_in addr;
int fd = 0;
int addrSize = sizeof(addr);
fd = socket(AF_INET, SOCK_DGRAM, 0);
if(fd < 0)
{
printf("%s, socket failed.\n", __FUNCTION__);
free(pUdp);
pUdp = NULL;
return NULL;
}
int on = 1;
setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = inet_addr(IP);
if( SERVER == isSerClint)
{
int ret = 0;
ret = bind(fd, (struct sockaddr *)&addr, addrSize);
if(-1 == ret)
{
perror("udp SERVER bind failed.\n");
free(pUdp);
pUdp = NULL;
return NULL;
}
else
{
printf("SERVER ip:%s\n", inet_ntoa(addr.sin_addr));
}
}
pUdp->fd = fd;
pUdp->addr = addr;
pUdp->isServerClinet = isSerClint;
return pUdp;
}
int udpSend(NET_UDP *pUdp, unsigned char *pData, int dataLen, int sendLenOneTime)
{
int lenIndex = 0;
int ret = 0;
struct sockaddr_in remoteAddr; //保存接收方的地址
while(1)
{
if( dataLen > sendLenOneTime)
{
ret = sendto( pUdp->fd, pData + lenIndex, sendLenOneTime, 0, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr));
if(ret < 0)
{
printf("%s, tcp send failed.\n", __FUNCTION__);
break;
}
else
{
dataLen -= sendLenOneTime;
lenIndex += sendLenOneTime;
}
}
else
{
sendto( pUdp->fd, pData + lenIndex, dataLen, 0, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr));
break;
}
}
return dataLen;
}
int udpRecv(NET_UDP *pUdp, unsigned char *pData, int recvLen)
{
struct sockaddr_in remoteAddr; //保存发送方的地址
int len = sizeof(remoteAddr);
return recvfrom( pUdp->fd, pData, recvLen, 0, (struct sockaddr*)&remoteAddr, &len);
}
int udpClose(NET_UDP *pUdp)
{
close(pUdp->fd);
free(pUdp);
pUdp = NULL;
return 1;
}