Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- TCP Server
- */
- #include <stdio.h>
- #include <stdlib.h>
- #ifdef __linux__
- // gcc tcp_main.c -w -o tcp_main && ./tcp_main
- #include <sys/socket.h>
- #include <netinet/in.h>
- #include <netinet/ip.h>
- #include <unistd.h>
- #elif _WIN32
- // compile with linker settings: "gcc tcp_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_STREAM, IPPROTO_TCP);
- printf("socket: %i\n", s);
- // bind()
- struct sockaddr_in srvAddr;
- srvAddr.sin_family = AF_INET;
- srvAddr.sin_port = htons(3334); // port
- srvAddr.sin_addr.s_addr = htonl(INADDR_ANY);
- int b = bind(s, &srvAddr, sizeof(srvAddr));
- printf("bind: %i\n", b);
- // listen()
- int queue = SOMAXCONN; // handle this amount of clients
- printf("listen: %i\n", listen(s, queue));
- // accept()
- struct sockaddr_in cliAddr;
- int size = sizeof(cliAddr);
- int cliSocket = accept(s, (struct socketaddr *)&cliAddr, &size);
- printf("listen sock: %i\n", cliSocket);
- char str[128];
- int r = recv(cliSocket, str, 100, 0);
- 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