Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- UDP Server
- */
- #include <stdio.h>
- #include <stdlib.h>
- #ifdef __linux__
- // gcc udp_main.c -w -o udp_main && ./udp_main
- #include <sys/socket.h>
- #include <netinet/in.h>
- #include <netinet/ip.h>
- #include <unistd.h>
- #elif _WIN32
- // compile with linker settings: "gcc udp_main.c -lws2_32"
- g++ main.cpp - lws2_32
- #define _WIN32_WINNT 0x0A00
- #include <winsock2.h>
- #include <ws2tcpip.h>
- #endif
- int main()
- {
- #ifdef _WIN32 // Win Only: Treiber Starten
- WSADATA wsaData;
- int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
- if (iResult != 0)
- {
- printf("WSAStartup failed: %d\n", iResult);
- return 1;
- }
- #endif
- // socket()
- int s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
- printf("socket: %i\n", s);
- // bind()
- struct sockaddr_in srvAddr;
- srvAddr.sin_family = AF_INET;
- srvAddr.sin_port = htons(51234); // port
- srvAddr.sin_addr.s_addr = htonl(INADDR_ANY);
- int b = bind(s, &srvAddr, sizeof(srvAddr));
- printf("bind: %i\n", b);
- // listen()
- struct sockaddr_in cliAddr;
- int size = sizeof(cliAddr);
- char str[128];
- int r = recvfrom(s, str, 100, 0, (struct sockaddr *)&cliAddr, sizeof(&size));
- printf("receive: %i\n", r);
- printf("data: %s\n", str);
- #ifdef __linux__
- close(s);
- #elif _WIN32 // Win Only: Treiber Beenden
- closesocket(s);
- int iReuslt = WSACleanup();
- #endif
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement