Last active
March 6, 2022 10:12
-
-
Save tiebingzhang/b25599f840318c97fd6d212d1ae91083 to your computer and use it in GitHub Desktop.
A simple TCP client in C
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 <stdio.h> | |
#include <unistd.h> | |
#include <netdb.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <sys/socket.h> | |
#define PORT 8080 | |
int main() | |
{ | |
int sockfd; | |
struct sockaddr_in servaddr; | |
// socket create and varification | |
sockfd = socket(AF_INET, SOCK_STREAM, 0); | |
if (sockfd == -1) { | |
printf("socket creation failed...\n"); | |
exit(0); | |
} | |
bzero(&servaddr, sizeof(servaddr)); | |
servaddr.sin_family = AF_INET; | |
servaddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK); | |
servaddr.sin_port = htons(PORT); | |
// connect the client socket to server socket | |
if (connect(sockfd, (struct sockaddr*)&servaddr, sizeof(servaddr)) != 0) { | |
printf("connection with the server failed...\n"); | |
exit(0); | |
} else{ | |
printf("connected to the server..\n"); | |
} | |
char buf[1024]; | |
int len = read(sockfd,buf,1024); | |
printf("read %d bytes from socket\n",len); | |
close(sockfd); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment