-
-
Save kvalv/c33b189c7f033ec5fc4aee9aed872b76 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <stdio.h> | |
| #include <stdlib.h> | |
| #include <string.h> | |
| #include <stdbool.h> | |
| #include <sys/types.h> | |
| #include <sys/socket.h> | |
| #include <netinet/in.h> | |
| #include <unistd.h> | |
| typedef struct UDP_message_t | |
| { | |
| int ip; | |
| int portNumber; | |
| char* message; | |
| int messageLength; | |
| } UDP_message_t; | |
| int listenForMessage (W int portNo, char* receiveBuffer, UDP_message_t* udpMessage, int maxBufferSize ) | |
| { | |
| struct sockaddr_in listenSocket, receiveSocket; | |
| //int ipAddressLengthInBytes = 16; | |
| int s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); | |
| if ( s == -1 ) | |
| { | |
| printf("Failed to create UDP server"); | |
| return -1; | |
| } | |
| memset( &listenSocket, 0, sizeof(struct sockaddr_in) ); | |
| listenSocket.sin_family = AF_INET; | |
| listenSocket.sin_port = htons(portNo); | |
| listenSocket.sin_addr.s_addr = htonl(INADDR_ANY); | |
| bool successfulBind = bind( s, (struct sockaddr*)&listenSocket, sizeof(struct sockaddr_in) ) != -1 ? true : false; | |
| if (!successfulBind) | |
| { | |
| printf("failed to bind"); | |
| return -1; | |
| } | |
| while(1) | |
| { | |
| printf("waiting for data \n"); | |
| fflush(stdout); | |
| int receiveLength; | |
| int slen = 16; | |
| receiveLength = recvfrom(s, receiveBuffer, 1024, 0, (struct sockaddr*) &receiveSocket, &slen); | |
| if ( receiveLength == -1 ) | |
| { | |
| printf("failed to receive message"); | |
| return -1; | |
| } | |
| else | |
| { | |
| printf("\nReceived data: "); | |
| int i; | |
| for ( i = 0; i < receiveLength; i++) | |
| { | |
| printf("%c", receiveBuffer[i]); | |
| } | |
| printf("\n"); | |
| printf("\n\n sender is %d:%d\n", receiveSocket.sin_addr.s_addr, receiveSocket.sin_port); | |
| } | |
| close(s); | |
| udpMessage->ip = ntohl(receiveSocket.sin_addr.s_addr); | |
| udpMessage->portNumber = ntohs(receiveSocket.sin_port); | |
| udpMessage->message = receiveBuffer; | |
| udpMessage->messageLength = receiveLength; | |
| return receiveLength; | |
| } | |
| } | |
| int main(int argc, char **argv) | |
| { | |
| int portNumber = atoi(argv[1]); | |
| char message[1024]; | |
| UDP_message_t* udpMsg; | |
| int numBytesReturned = listenForMessage( portNumber, message, udpMsg, 1024 ); | |
| printf("\n\number of bytes returned %d", numBytesReturned); | |
| return 0; | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment