⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 udpsend.c

📁 发送UDP的源代码
💻 C
字号:
/**
***
***  UDPsend.c
***
***  Kelly Hall
***  JK Microsystems, Inc.
***  15 Jun 00
***
***  Boilerplate for a simple UDP application
***    Open a UDP socket to a known host
***    Send a packet of junk every 2 seconds
***
**/

#include <stdio.h>
#include <conio.h>
#include <time.h>
#include "tcp.h"

int main(void) {
	udp_Socket sendSock;            // our socket variable
	longword   destAddr;            // hold the resolved IP address of the target
	word       destPort = 4000;     // destination port number
	char      *destHost = "209.233.102.231";   // hostname of the target
	time_t     lastTime;            // the time we last sent a packet
	char       sendBuff[1024];      // our buffer for packets that we send
	int        buffLen;             // number of bytes in our buffer
	int        sentLen;             // number of bytes we just sent
	int        pktCnt;              // keep track of how many packets we've sent
	int        errFlag;             // error flag

	sock_init();                    // wake up the TCP/IP stack

	/**
	Resolve the host name into an IP address.
	This is needed even for host names in dotted number format.
	**/
	if( !(destAddr = resolve(destHost)) ) {  // look up the number for this host
		printf("Error resolving hostname '%s'\n", destHost);
		return -1;
	}

	/**
	Create a virtual socket for our UDP messages.
	This call determines which port we send from, the destination address, and
	  the destination port.
	We request that we send from port 0, but the stack will substitute a real
	  (random) port number.  We could specify a particular number if we cared.
	We need to specify a destination port, however.
	If we didn't care about reliability, we could open the socket once,
	  outside of this loop.  However, if we get PORT UNREACHABLE errors later
	  on, we need to re-open the socket.  It's easy and (usually) fast enough
	  that we can re-open the socket every time we need to send a packet.
	**/
	if( !udp_open(&sendSock, 0, destAddr, destPort, NULL) ) {
		printf("Error opening the UDP socket\n");
		return -1;
	}

	printf("Starting main loop - press a key to exit\n");
	errFlag = 0;                 // no errors so far
	pktCnt  = 0;                 // initilize the counter
	lastTime = time(NULL);       // pretend we sent a packet
	while( !kbhit() ) {          // loop until a key is pressed

		tcp_tick(NULL);           // give the TCP/IP stack some CPU cycles

		if( time(NULL) >= (lastTime + 2) ) {
			// time to send a packet

			/**
			Construct the buffer that we want to send.  This needs to match what
			  the destination program expects to receive, of course.  But for our
			  example we can send anything we care to.  I choose to send a simple
			  text string.
			**/
			buffLen = sprintf(sendBuff, "This is a test: sending packet %d\n", pktCnt);


			/**
			Now we send the buffer over the UDP socket.  Since we don't want to
			  be delayed on this transfer, we use sock_fastwrite().
			The cast (byte *) is just to shut up the fussy compiler.
			**/
			sentLen = sock_fastwrite(&sendSock, (byte *)sendBuff, buffLen);

			if( sentLen != buffLen ) {
         	printf("error detected - not enough bytes sent\n");
				errFlag = 1;
			} else {
				pktCnt++;
			}

			lastTime = time(NULL);
		}

		/**
		Because errors can occur that would invalidate our socket (such as the
		  destination computer refusing our packet, it's prudent to query the
		  socket for errors periodically.
		In our case, if we detect an error we'll simply close the socket and
		  re-open it.
		**/
		if( errFlag || sockerr(&sendSock) ) {
			printf("error detected on socket - cycling the socket\n");
			sock_close( &sendSock );
			if( !udp_open(&sendSock, 0, destAddr, destPort, NULL) ) {
				printf("Error re-opening the UDP socket\n");
				return -1;
			}
			errFlag = 0;  // clear the flag
         pktCnt--;     // decrement the packet count
		}

		/**
		Any other code that needs to run can be inserted below.
		**/

	}

	/**
	We're nice people - we close our sockets when we're finished,
	  although it is *not* required.
	**/
	sock_close( &sendSock );

	return 0;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -