Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- *
- * Compilation: gcc -Wall ./tcp-server.c -o ./tcp-server
- * Usage: ./tcp-server
- *
- *
- */
- #include <netinet/in.h>
- #include <stdlib.h>
- #include <string.h>
- #include <sys/socket.h>
- #include <unistd.h>
- #include <stdio.h>
- #include <netdb.h>
- int main(int argc, char** argv) {
- if (argc != 3) {
- printf("usage: ./tcp-server <IP> <PORT>\n");
- return -1;
- }
- socklen_t sl;
- int sfd, cfd, on = 1;
- struct sockaddr_in saddr, caddr;
- memset(&saddr, 0, sizeof(saddr));
- saddr.sin_family = AF_INET;
- saddr.sin_addr.s_addr = INADDR_ANY;
- saddr.sin_port = htons(1234);
- sfd = socket(PF_INET, SOCK_STREAM, 0);
- setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, (char*) &on, sizeof(on));
- bind(sfd, (struct sockaddr*) &saddr, sizeof(saddr));
- listen(sfd, 5);
- unsigned long long int asdf = 0;
- while(1) {
- memset(&caddr, 0, sizeof(caddr));
- sl = sizeof(caddr);
- cfd = accept(sfd, (struct sockaddr*) &caddr, &sl);
- char buff[256] = {0};
- int sz = read(cfd, &buff, 256);
- if (sz <= 0) {
- printf("something went wrong!");
- }
- printf("[got:]\t%s\n", buff);
- int csfd;
- struct sockaddr_in csaddr;
- struct hostent* caddrent;
- caddrent = gethostbyname(argv[1]);
- csfd = socket(PF_INET, SOCK_STREAM, 0);
- memset(&csaddr, 0, sizeof(csaddr));
- csaddr.sin_family = AF_INET;
- csaddr.sin_port = htons(atoi(argv[2]));
- memcpy(&csaddr.sin_addr.s_addr, caddrent->h_addr, caddrent->h_length);
- connect(csfd, (struct sockaddr*) &csaddr, sizeof(csaddr));
- write(csfd, &buff, sz);
- close(csfd);
- }
- close(sfd);
- return EXIT_SUCCESS;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement