This code works when using it locally(ip = 127.0.0.1), but doesn’t work when testing it with a real ip.
It doesn’t work when I host the server, nor when my friend hosts the server.
My friend suspects that it’s a firewall issue, but we both have it inactive – I checked with sudo ufw status
, he with sudo netstat -ntlp
.
// client.c
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
int main() {
int port = 8080;
const char *ip = "127.0.0.1"; // Changed this to the real ip to test it.
int sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock == -1) {
return 2;
}
struct sockaddr_in hint;
hint.sin_family = AF_INET;
hint.sin_port = htons(port);
inet_pton(AF_INET, ip, &hint.sin_addr);
int connResult = connect(sock, (struct sockaddr *)&hint, sizeof(hint));
if (connResult == -1) {
int status = shutdown(sock, SHUT_RDWR);
if (status == 0) {
status = close(sock);
}
return status;
}
while (1) {
const char *msg = "ping";
int sendResult = send(sock, msg, strlen(msg) + 1, 0);
if (sendResult == -1)
{
return 3;
}
usleep(1000 * 2000);
}
/* unreachable */
int status = shutdown(sock, SHUT_RDWR);
if (status == 0) {
status = close(sock);
}
return status;
}
// server.c
#include <arpa/inet.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#define BUFF_SIZE 4096
int main() {
int port = 8080;
int status;
while (1) {
int listening = socket(AF_INET, SOCK_STREAM, 0);
if (listening == -1) {
return 1;
}
struct sockaddr_in hint;
hint.sin_family = AF_INET;
hint.sin_port = htons(port);
hint.sin_addr.s_addr = INADDR_ANY;
if (bind(listening, (struct sockaddr *)&hint, sizeof(hint)) == -1){
return 1;
}
listen(listening, SOMAXCONN);
struct sockaddr_in client;
unsigned int clientSize = sizeof(client);
int clientSocket =
accept(listening, (struct sockaddr *)&client, &clientSize);
int status = 0;
status = shutdown(listening, SHUT_RDWR);
if (status == 0) {
status = close(listening);
}
char buff[BUFF_SIZE];
while (1) {
memset(buff, 0, BUFF_SIZE);
int bytesReceived = recv(clientSocket, buff, BUFF_SIZE, 0);
if (bytesReceived == -1) {
return 2;
}
if (bytesReceived > BUFF_SIZE) {
return 3;
}
if (bytesReceived > 0) {
printf("A client sent: %sn", buff);
} else {
break;
}
usleep(1000 * 1000);
}
status = shutdown(clientSocket, SHUT_RDWR);
if (status == 0) {
status = close(clientSocket);
}
}
return 0;
}
Compile commands:
gcc server.c -o server
gcc client.c -o client
New contributor
Sam is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
5