Skip to content

Instantly share code, notes, and snippets.

@SkrewEverything
Last active June 20, 2023 11:56
Show Gist options
  • Select an option

  • Save SkrewEverything/e31096ac01aa67d28eca283dbbbf96a1 to your computer and use it in GitHub Desktop.

Select an option

Save SkrewEverything/e31096ac01aa67d28eca283dbbbf96a1 to your computer and use it in GitHub Desktop.
Simple TCP Client
// Client side C/C++ program to demonstrate Socket programming
#include <stdio.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <unistd.h>
#include <netinet/in.h>
#include <string.h>
#include <arpa/inet.h>
#define PORT 8080
int main(int argc, char const *argv[])
{
int sock = 0; long valread;
struct sockaddr_in serv_addr;
char *hello = "Hello from client";
char buffer[1024] = {0};
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
printf("\n Socket creation error \n");
return -1;
}
memset(&serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(PORT);
// Convert IPv4 and IPv6 addresses from text to binary form
if(inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr)<=0)
{
printf("\nInvalid address/ Address not supported \n");
return -1;
}
if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
{
printf("\nConnection Failed \n");
return -1;
}
send(sock , hello , strlen(hello) , 0 );
printf("Hello message sent\n");
valread = read( sock , buffer, 1024);
printf("%s\n",buffer );
return 0;
}
@IanKatsy
Copy link

IanKatsy commented Jun 15, 2023

Hello there, I got here from this article.

Shouldn't line 24 be memset(&serv_addr, 0, sizeof(serv_addr)); . It shouldn't really matter cause the struct gets filled (don't know if this is the correct term) later, but you never know.

@SkrewEverything
Copy link
Author

@IanKatsy, you are right! It should be 0. But as you said, it didn't cause any issues because we are filling it up later. But thanks for catching the bug. I'll fix it

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment