Last active
October 18, 2016 11:44
-
-
Save polaroi8d/75806482cd632de307b1e6034854acd5 to your computer and use it in GitHub Desktop.
Using socket in C with structure sending // CLIENT
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
/* tcpclient.c */ | |
#include <sys/socket.h> | |
#include <sys/types.h> | |
#include <netinet/in.h> | |
#include <netdb.h> | |
#include <stdio.h> | |
#include <string.h> | |
#include <stdlib.h> | |
#include <unistd.h> | |
#include <errno.h> | |
typedef struct | |
{ | |
char *msg; | |
size_t msg_lenght; | |
uint16_t type; | |
} package; | |
int main() | |
{ | |
int sock, bytes_recieved; | |
char send_data[1024],recv_data[1024]; | |
struct hostent *host; | |
struct sockaddr_in server_addr; | |
host = gethostbyname("127.0.0.1"); | |
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == -1) { | |
perror("Socket"); | |
exit(1); | |
} | |
server_addr.sin_family = AF_INET; | |
server_addr.sin_port = htons(5000); | |
server_addr.sin_addr = *((struct in_addr *)host->h_addr); | |
bzero(&(server_addr.sin_zero),8); | |
if (connect(sock, (struct sockaddr *)&server_addr, | |
sizeof(struct sockaddr)) == -1) | |
{ | |
perror("Connect"); | |
exit(1); | |
} | |
package PCKG; | |
PCKG.msg = " "; | |
PCKG.msg_lenght = 0; | |
PCKG.type = 0; | |
bytes_recieved = recv(sock,&PCKG,1024,0); | |
// recv_data[bytes_recieved] = '\0'; | |
printf("\nMSG = %s \nSTRLEN = %zu\n TYPE = %d\n", PCKG.msg, PCKG.msg_lenght, PCKG.type); | |
close(sock); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment