C language UDP transfer system source code
- 2020-06-03 07:49:29
- OfStack
The example of this paper shares the specific code of C language UDP transmission system for your reference, the specific content is as follows
/* Load library file */
#pragma comment( lib, "ws2_32.lib" )
/* Load header file */
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdio.h>
#include <stdlib.h>
/* Define multicast constants */
#define MCASTADDR "224.3.5.8"
#define MCASTPORT 25000
#define BUFSIZE 1024
#define MCOUNT 10
/* Defining broadcast constants */
#define BCASTPORT 5050
#define BCOUNT 10
/* Define broadcast global variables */
SOCKET socketBro;
SOCKET socketRec;
struct sockaddr_in addrBro;
struct sockaddr_in addrRec;
BOOL broadSendFlag;
BOOL broadFlag;
DWORD bCount;
DWORD bcastAddr;
short bPort;
/* Define multicast global variables */
SOCKET socketMul;
SOCKET sockJoin;
struct sockaddr_in addrLocal;
struct sockaddr_in addrMul;
BOOL multiSendFlag;
BOOL bLoopBack;
BOOL multiFlag;
DWORD dwInterface;
DWORD dwMulticastGroup;
DWORD mCount;
short mPort;
/* Custom function */
void initial();
void GetArgments(int argc, char **argv);
void userHelpAll();
void userHelpBro();
void userHelpMul();
void broadcastSend();
void broadcastRec();
void mulControl();
void multicastSend();
void multicastRec();
/* Initializes global variable functions */
void initial()
{
/* Initializes broadcast global variables */
bPort = BCASTPORT;
bCount = BCOUNT;
bcastAddr = INADDR_BROADCAST;
broadSendFlag = FALSE;
broadFlag = FALSE;
multiFlag = FALSE;
/* Initializes a multicast global variable */
dwInterface = INADDR_ANY;
dwMulticastGroup = inet_addr(MCASTADDR);
mPort = MCASTPORT;
mCount = MCOUNT;
multiSendFlag = FALSE;
bLoopBack = FALSE;
}
/* Parameter acquisition function */
void GetArgments(int argc, char **argv)
{
int i;
/* If the number of arguments is less than 2 a */
if(argc<=1)
{
userHelpAll();
return ;
}
/* Get broadcast options */
if(argv[1][0]=='-'&&argv[1][1]=='b')
{
/* The broadcast flag is set to true */
broadFlag = TRUE;
for(i=2; i < argc ;i++)
{
if (argv[i][0] == '-')
{
switch (tolower(argv[i][1]))
{
/* If it's the sender */
case 's':
broadSendFlag = TRUE;
break;
/* Broadcast address */
case 'h':
if (strlen(argv[i]) > 3)
bcastAddr = inet_addr(&argv[i][3]);
break;
/* Broadcast port number */
case 'p':
if (strlen(argv[i]) > 3)
bPort = atoi(&argv[i][3]);
break;
/* radio ( Receive or send ) The number of */
case 'n':
bCount = atoi(&argv[i][3]);
break;
/* Other cases show user help, terminating the program */
default:
{
userHelpBro();
ExitProcess(-1);
}
break;
}
}
}
return ;
}
/* Gets the multicast option */
if(argv[1][0]=='-'&&argv[1][1]=='m')
{
/* The multicast flag is set to true */
multiFlag = TRUE;
for(i=2; i < argc ;i++)
{
if (argv[i][0] == '-')
{
switch (tolower(argv[i][1]))
{
/* If it's the sender */
case 's':
multiSendFlag = TRUE;
break;
/* The multicast address */
case 'h':
if (strlen(argv[i]) > 3)
dwMulticastGroup = inet_addr(&argv[i][3]);
break;
/* Local interface address */
case 'i':
if (strlen(argv[i]) > 3)
dwInterface = inet_addr(&argv[i][3]);
break;
/* Multicast port number */
case 'p':
if (strlen(argv[i]) > 3)
mPort = atoi(&argv[i][3]);
break;
/* The loopback flag is set to true */
case 'l':
bLoopBack = TRUE;
break;
/* send ( receive ) The number of */
case 'n':
mCount = atoi(&argv[i][3]);
break;
/* In other cases, show user help and terminate the program */
default:
userHelpMul();
break;
}
}
}
}
return;
}
/* Global user help functions */
void userHelpAll()
{
printf("Please choose broadcast[-b] or multicast[-m] !\n");
printf("userHelpAll: -b [-s][p][-h][-n] | -m[-s][-h][-p][-i][-l][-n]\n");
userHelpBro();
userHelpMul();
}
/* Broadcast user help functions */
void userHelpBro()
{
printf("Broadcast: -b -s:str -p:int -h:str -n:int\n");
printf(" -b Start the broadcast program.\n");
printf(" -s Act as server (send data); otherwise\n");
printf(" receive data. Default is receiver.\n");
printf(" -p:int Port number to use\n ");
printf(" The default port is 5050.\n");
printf(" -h:str The decimal broadcast IP address.\n");
printf(" -n:int The Number of messages to send/receive.\n");
printf(" The default number is 10.\n");
}
/* Multicast user help function */
void userHelpMul()
{
printf("Multicast: -m -s -h:str -p:int -i:str -l -n:int\n");
printf(" -m Start the multicast program.\n");
printf(" -s Act as server (send data); otherwise\n");
printf(" receive data. Default is receiver.\n");
printf(" -h:str The decimal multicast IP address to join\n");
printf(" The default group is: %s\n", MCASTADDR);
printf(" -p:int Port number to use\n");
printf(" The default port is: %d\n", MCASTPORT);
printf(" -i:str Local interface to bind to; by default \n");
printf(" use INADDRY_ANY\n");
printf(" -l Disable loopback\n");
printf(" -n:int Number of messages to send/receive\n");
ExitProcess(-1);
}
/* Broadcast message sending function */
void broadcastSend()
{
/* Set the broadcast message */
char *smsg="The message received is from sender!";
BOOL opt=TRUE;
int nlen=sizeof(addrBro);
int ret;
DWORD i=0;
/* create UDP The socket */
socketBro=WSASocket(AF_INET,SOCK_DGRAM,0,NULL,0,WSA_FLAG_OVERLAPPED);
/* If the creation fails */
if(socketBro==INVALID_SOCKET)
{
printf("Create socket failed:%d\n",WSAGetLastError());
WSACleanup();
return;
}
/* Set various options for broadcast addresses */
addrBro.sin_family=AF_INET;
addrBro.sin_addr.s_addr=bcastAddr;
addrBro.sin_port=htons(bPort);
/* Set the socket to broadcast type */
if (setsockopt(socketBro,SOL_SOCKET,SO_BROADCAST,(char FAR *)&opt,
sizeof(opt))==SOCKET_ERROR)
/* If the setup fails */
{
printf("setsockopt failed:%d",WSAGetLastError());
closesocket(socketBro);
WSACleanup();
return;
}
/* Loop send message */
while(i<bCount)
{
/* delay 1 seconds */
Sleep(1000);
/* Send a message from a broadcast address */
ret=sendto(socketBro,smsg,256,0,(struct sockaddr*)&addrBro,nlen);
/* If the send fails */
if(ret==SOCKET_ERROR)
printf("Send failed:%d",WSAGetLastError());
/* If you send it successfully */
else
{
printf("Send message %d!\n",i);
}
i++;
}
/* After sending, close the socket and release the occupied resources */
closesocket(socketBro);
WSACleanup();
}
/* Broadcast message receiving function */
void broadcastRec()
{
BOOL optval = TRUE;
int addrBroLen;
char buf[256];
DWORD i=0;
/* This address is used to bind sockets */
addrRec.sin_family=AF_INET;
addrRec.sin_addr.s_addr=0;
addrRec.sin_port=htons(bPort);
/* This address is used to receive messages broadcast over the network */
addrBro.sin_family=AF_INET;
addrBro.sin_addr.s_addr=bcastAddr;
addrBro.sin_port=htons(bPort);
addrBroLen=sizeof(addrBro);
// create UDP The socket
socketRec=socket(AF_INET,SOCK_DGRAM,0);
/* If the creation fails */
if(socketRec==INVALID_SOCKET)
{
printf("Create socket error:%d",WSAGetLastError());
WSACleanup();
return;
}
/* Set the socket to a reusable type */
if(setsockopt(socketRec,SOL_SOCKET,SO_REUSEADDR,(char FAR *)&optval,
sizeof(optval))==SOCKET_ERROR)
/* If the setup fails */
{
printf("setsockopt failed:%d",WSAGetLastError());
closesocket(socketRec);
WSACleanup();
return;
}
/* Bind sockets and addresses */
if(bind(socketRec,(struct sockaddr *)&addrRec,
sizeof(struct sockaddr_in))==SOCKET_ERROR)
/* If the binding fails */
{
printf("bind failed with: %d\n", WSAGetLastError());
closesocket(socketRec);
WSACleanup();
return ;
}
/* Receive a message from a broadcast address */
while(i<bCount)
{
recvfrom(socketRec,buf,256,0,(struct sockaddr FAR *)&addrBro,(int FAR *)&addrBroLen);
/* delay 2 seconds */
Sleep(2000);
/* Output a message received in the buffer */
printf("%s\n",buf);
/* Case buffer */
ZeroMemory(buf,256);
i++;
}
/* After receiving, close the socket and release the occupied resources */
closesocket(socketRec);
WSACleanup();
}
/* Multicast control function */
void mulControl()
{
int optval;
/* create UDP Socket for multicast */
if ((socketMul = WSASocket(AF_INET, SOCK_DGRAM, 0, NULL, 0,
WSA_FLAG_MULTIPOINT_C_LEAF
| WSA_FLAG_MULTIPOINT_D_LEAF
| WSA_FLAG_OVERLAPPED)) == INVALID_SOCKET)
{
printf("socket failed with: %d\n", WSAGetLastError());
WSACleanup();
return ;
}
/* Set the local interface address */
addrLocal.sin_family = AF_INET;
addrLocal.sin_port = htons(mPort);
addrLocal.sin_addr.s_addr = dwInterface;
/* will UDP The socket is bound to the local address */
if (bind(socketMul, (struct sockaddr *)&addrLocal,
sizeof(addrLocal)) == SOCKET_ERROR)
/* If the binding fails */
{
printf("bind failed with: %d\n", WSAGetLastError());
closesocket(socketMul);
WSACleanup();
return ;
}
/* Set various options for multicast addresses */
addrMul.sin_family = AF_INET;
addrMul.sin_port = htons(mPort);
addrMul.sin_addr.s_addr = dwMulticastGroup;
/* To reset TTL value */
optval = 8;
/* To set multicast data TTL( There is time ) Value. By default, TTL The value is 1*/
if (setsockopt(socketMul, IPPROTO_IP, IP_MULTICAST_TTL,
(char *)&optval, sizeof(int)) == SOCKET_ERROR)
/* If the setup fails */
{
printf("setsockopt(IP_MULTICAST_TTL) failed: %d\n",WSAGetLastError());
closesocket(socketMul);
WSACleanup();
return ;
}
/* If the return option is specified */
if (bLoopBack)
{
/* Set the return option to false to prohibit sending data back to the local interface */
optval = 0;
if (setsockopt(socketMul, IPPROTO_IP, IP_MULTICAST_LOOP,
(char *)&optval, sizeof(optval)) == SOCKET_ERROR)
/* If the setup fails */
{
printf("setsockopt(IP_MULTICAST_LOOP) failed: %d\n",
WSAGetLastError());
closesocket(socketMul);
WSACleanup();
return ;
}
}
/* Join a multicast group */
if ((sockJoin = WSAJoinLeaf(socketMul, (SOCKADDR *)&addrMul,
sizeof(addrMul), NULL, NULL, NULL, NULL,
JL_BOTH)) == INVALID_SOCKET)
/* If it doesn't work */
{
printf("WSAJoinLeaf() failed: %d\n", WSAGetLastError());
closesocket(socketMul);
WSACleanup();
return ;
}
}
/* Multicast message sending function */
void multicastSend()
{
TCHAR sendbuf[BUFSIZE];
DWORD i;
int ret;
mulControl();
/* send mCount message */
for(i = 0; i < mCount; i++)
{
/* Writes the message to be sent to the send buffer */
sprintf(sendbuf, "server 1: This is a test: %d", i);
ret=sendto(socketMul, (char *)sendbuf, strlen(sendbuf), 0,
(struct sockaddr *)&addrMul, sizeof(addrMul));
/* If the send fails */
if(ret==SOCKET_ERROR)
{
printf("sendto failed with: %d\n",WSAGetLastError());
closesocket(sockJoin);
closesocket(socketMul);
WSACleanup();
return ;
}
/* If you send it successfully */
else
printf("Send message %d\n",i);
Sleep(500);
}
/* Close the socket and release the resource */
closesocket(socketMul);
WSACleanup();
}
/* Multicast message receiving function */
void multicastRec()
{
DWORD i;
struct sockaddr_in from;
TCHAR recvbuf[BUFSIZE];
int ret;
int len = sizeof(struct sockaddr_in);
mulControl();
/* receive mCount message */
for(i = 0; i < mCount; i++)
{
/* Writes the received message to the receive buffer */
if ((ret = recvfrom(socketMul, recvbuf, BUFSIZE, 0,
(struct sockaddr *)&from, &len)) == SOCKET_ERROR)
/* If the reception is unsuccessful */
{
printf("recvfrom failed with: %d\n",WSAGetLastError());
closesocket(sockJoin);
closesocket(socketMul);
WSACleanup();
return ;
}
/* Receives successfully, outputs the received message */
recvbuf[ret] = 0;
printf("RECV: '%s' from <%s>\n", recvbuf,inet_ntoa(from.sin_addr));
}
/* Close the socket and release the resource */
closesocket(socketMul);
WSACleanup();
}
/* The main function */
int main(int argc, char **argv)
{
WSADATA wsd;
initial();
GetArgments(argc, argv);
/* Initialize the Winsock*/
if (WSAStartup(MAKEWORD(2, 2), &wsd) != 0)
{
printf("WSAStartup() failed\n");
return -1;
}
/* If you are executing a broadcast program */
if(broadFlag)
{
/* Send a message as the sender */
if(broadSendFlag)
{
broadcastSend();
return 0;
}
/* Receive the message as a receiver */
else
{
broadcastRec();
return 0;
}
}
/* If you are executing a multicast program */
if(multiFlag)
{
/* Send a message as the sender */
if(multiSendFlag)
{
multicastSend();
return 0;
}
/* Receive the message as a receiver */
else
{
multicastRec();
return 0;
}
}
return 0;
}