Skip to content

Instantly share code, notes, and snippets.

@ssrlive
Last active March 2, 2018 12:57
Show Gist options
  • Save ssrlive/6aec4c230e474aabba3f434e0fc7442b to your computer and use it in GitHub Desktop.
Save ssrlive/6aec4c230e474aabba3f434e0fc7442b to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#if defined(_WIN32)
#include <WinSock2.h>
#include <ws2tcpip.h>
#pragma comment(lib, "Ws2_32.lib")
#else
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <unistd.h>
#endif
#define BUF_SIZE 1024
int main(int argc, char *argv[]) {
struct sockaddr_in server;
socklen_t len = sizeof(struct sockaddr_in);
char buf[BUF_SIZE];
struct hostent *host;
int n, s, port;
{
#if defined(_WIN32)
WSADATA wsaData;
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != NO_ERROR) {
printf("Error at WSAStartup()\n");
return 1;
}
#endif
}
if (argc < 4) {
fprintf(stderr, "Usage: %s <host> <port> <message>\n", argv[0]);
return 1;
}
host = gethostbyname(argv[1]);
if (host == NULL) {
perror("gethostbyname");
return 1;
}
port = atoi(argv[2]);
/* initialize socket */
if ((s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) {
perror("socket");
return 1;
}
/* initialize server addr */
memset((char *)&server, 0, sizeof(struct sockaddr_in));
server.sin_family = AF_INET;
server.sin_port = htons(port);
server.sin_addr = *((struct in_addr*) host->h_addr);
/* send message */
if (sendto(s, argv[3], strlen(argv[3]), 0, (struct sockaddr *) &server, len) == -1) {
perror("sendto()");
return 1;
}
/* receive echo.
** for single message, "while" is not necessary. But it allows the client
** to stay in listen mode and thus function as a "server" - allowing it to
** receive message sent from any endpoint.
*/
(n = recvfrom(s, buf, BUF_SIZE, 0, (struct sockaddr *) &server, &len));
if (n > 0) {
printf("Received from %s:%d: ",
inet_ntoa(server.sin_addr),
ntohs(server.sin_port));
fflush(stdout);
buf[n] = 0;
printf("%s\n", buf);
}
#if defined(_WIN32)
closesocket(s);
#else
close(s);
#endif
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment