tcp/quic lab finished
This commit is contained in:
53
network/tcpquiclab/tcp_client.c
Normal file
53
network/tcpquiclab/tcp_client.c
Normal file
@@ -0,0 +1,53 @@
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
#include <arpa/inet.h>
|
||||
#include <sys/socket.h>
|
||||
|
||||
#define PORT 8080
|
||||
#define SERVER_IP "127.0.0.1"
|
||||
#define BUFFER_SIZE 1024
|
||||
|
||||
int main() {
|
||||
int sock = 0;
|
||||
struct sockaddr_in serv_addr;
|
||||
const char *hello = "Hello from TCP Client";
|
||||
char buffer[BUFFER_SIZE] = {0};
|
||||
|
||||
// 1. Create socket
|
||||
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
|
||||
printf("\n Socket creation error \n");
|
||||
return -1;
|
||||
}
|
||||
|
||||
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, SERVER_IP, &serv_addr.sin_addr) <= 0) {
|
||||
printf("\nInvalid address/ Address not supported \n");
|
||||
return -1;
|
||||
}
|
||||
|
||||
// 2. Connect to server
|
||||
if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) {
|
||||
printf("\nConnection Failed \n");
|
||||
return -1;
|
||||
}
|
||||
|
||||
// 3. Send data
|
||||
send(sock, hello, strlen(hello), 0);
|
||||
printf("Message sent to server: %s\n", hello);
|
||||
|
||||
// 4. Receive response
|
||||
int valread = read(sock, buffer, BUFFER_SIZE);
|
||||
if (valread > 0) {
|
||||
printf("Server response: %s\n", buffer);
|
||||
}
|
||||
|
||||
// 5. Close socket
|
||||
close(sock);
|
||||
|
||||
return 0;
|
||||
}
|
||||
Reference in New Issue
Block a user