Created
July 21, 2022 03:45
-
-
Save twopoint718/c78cb1f1c0b2702d0aaeb0b156b91ca4 to your computer and use it in GitHub Desktop.
This file contains 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 <arpa/inet.h> | |
#include <assert.h> | |
#include <netinet/ip.h> | |
#include <stdio.h> | |
#include <string.h> | |
#include <sys/socket.h> | |
#include <sys/types.h> | |
#include <unistd.h> | |
int main() { | |
char buf[1024]; | |
int err, num, numleft, sockfd, newsockfd; | |
unsigned int client_len; | |
struct sockaddr_in client_addr; | |
struct sockaddr_in serv_addr; | |
uint16_t port = 8080; | |
memset(&serv_addr, 0, sizeof(serv_addr)); | |
memset(&client_addr, 0, sizeof(client_addr)); | |
client_len = sizeof(client_addr); | |
strcpy(buf, "Hello world!\n"); | |
serv_addr.sin_family = AF_INET; | |
serv_addr.sin_port = htons(port); | |
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); | |
sockfd = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); assert(sockfd != -1); | |
err = bind(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)); assert(err == 0); | |
err = listen(sockfd, 10); assert(err == 0); | |
printf("Listening on %s:%d\n", inet_ntoa(serv_addr.sin_addr), port); | |
for(;;) { | |
newsockfd = accept(sockfd, (struct sockaddr *)&client_addr, &client_len); assert(newsockfd != -1); | |
printf("Connection from %s\n", inet_ntoa(client_addr.sin_addr)); | |
numleft = strlen(buf); | |
while(numleft > 0) { | |
num = write(newsockfd, buf, strlen(buf)); assert(num >= 0); | |
numleft -= num; | |
} | |
close(newsockfd); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment