Im trying to send a image using socket but I have to send the file name as well. Im using a code that i send the file but when I send the file name i receive some strange characters in client.
Client:
#define PORT 20000
#define LENGTH 512
int main(int argc, char *argv[]){
int sockfd;
int nsockfd;
char revbuf[LENGTH];
struct sockaddr_in remote_addr;
/* Get the Socket file descriptor */
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
fprintf(stderr, "ERROR: Failed to obtain Socket Descriptor! (errno = %d)\n",errno);
exit(1);
}
/* Fill the socket address struct */
remote_addr.sin_family = AF_INET;
remote_addr.sin_port = htons(PORT);
inet_pton(AF_INET, "127.0.0.1", &remote_addr.sin_addr);
bzero(&(remote_addr.sin_zero), 8);
/* Try to connect the remote */
if (connect(sockfd, (struct sockaddr *)&remote_addr, sizeof(struct sockaddr)) == -1)
{
fprintf(stderr, "ERROR: Failed to connect to the host! (errno = %d)\n",errno);
exit(1);
}
else
printf("[Client] Connected to server at port %d...ok!\n", PORT);
/* Send File to Server */
//if(!fork())
//{
char* fs_name = "house.jpg";
char sdbuf[LENGTH];
char buffer[256];
int n;
fgets(buffer,255,stdin);
bzero(buffer,256);
n = write(sockfd,buffer, strlen(buffer));
if(n<0) printf("Error: sending filename");
printf("[Client] Sending %s to the Server... ", fs_name);
FILE *fs = fopen(fs_name, "r");
if(fs == NULL)
{
printf("ERROR: File %s not found.\n", fs_name);
exit(1);
}
bzero(sdbuf, LENGTH);
int fs_block_sz;
while((fs_block_sz = fread(sdbuf, sizeof(char), LENGTH, fs)) > 0)
{
if(send(sockfd, sdbuf, fs_block_sz, 0) < 0)
{
fprintf(stderr, "ERROR: Failed to send file %s. (errno = %d)\n", fs_name, errno);
break;
}
bzero(sdbuf, LENGTH);
}
printf("Ok File %s from Client was Sent!\n", fs_name);
//}
close (sockfd);
printf("[Client] Connection lost.\n");
return (0);
}
Part of client that sends the text:
char buffer[256];
int n;
fgets(buffer,255,stdin);
bzero(buffer,256);
n = write(sockfd,buffer, strlen(buffer));
if(n<0) printf("Error: sending filename");
Server:
#define PORT 20000
#define BACKLOG 5
#define LENGTH 512
int main ()
{
int sockfd;
int nsockfd;
int num;
int sin_size;
struct sockaddr_in addr_local; /* client addr */
struct sockaddr_in addr_remote; /* server addr */
char revbuf[LENGTH];
/* Get the Socket file descriptor */
if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1 )
{
fprintf(stderr, "ERROR: Failed to obtain Socket Descriptor. (errno = %d)\n", errno);
exit(1);
}
else
printf("[Server] Obtaining socket descriptor successfully.\n");
/* Fill the client socket address struct */
addr_local.sin_family = AF_INET; // Protocol Family
addr_local.sin_port = htons(PORT); // Port number
addr_local.sin_addr.s_addr = INADDR_ANY; // AutoFill local address
bzero(&(addr_local.sin_zero), 8); // Flush the rest of struct
/* Bind a special Port */
if( bind(sockfd, (struct sockaddr*)&addr_local, sizeof(struct sockaddr)) == -1 )
{
fprintf(stderr, "ERROR: Failed to bind Port. (errno = %d)\n", errno);
exit(1);
}
else
printf("[Server] Binded tcp port %d in addr 127.0.0.1 sucessfully.\n",PORT);
/* Listen remote connect/calling */
if(listen(sockfd,BACKLOG) == -1)
{
fprintf(stderr, "ERROR: Failed to listen Port. (errno = %d)\n", errno);
exit(1);
}
else
printf ("[Server] Listening the port %d successfully.\n", PORT);
int success = 0;
while(success == 0)
{
sin_size = sizeof(struct sockaddr_in);
/* Wait a connection, and obtain a new socket file despriptor for single connection */
if ((nsockfd = accept(sockfd, (struct sockaddr *)&addr_remote, &sin_size)) == -1)
{
fprintf(stderr, "ERROR: Obtaining new Socket Despcritor. (errno = %d)\n", errno);
exit(1);
}
else
printf("[Server] Server has got connected from %s.\n", inet_ntoa(addr_remote.sin_addr));
char buffer[256];
bzero(buffer,256);
int n = 0;
n = read(nsockfd, buffer, 255);
if (n < 0) error("ERROR reading from socket");
printf("msg: %s\n",buffer);
/*Receive File from Client */
char* fr_name = "/house.jpg";
FILE *fr = fopen(fr_name, "a");
if(fr == NULL)
printf("File %s Cannot be opened file on server.\n", fr_name);
else
{
bzero(revbuf, LENGTH);
int fr_block_sz = 0;
while((fr_block_sz = recv(nsockfd, revbuf, LENGTH, 0)) > 0)
{
int write_sz = fwrite(revbuf, sizeof(char), fr_block_sz, fr);
if(write_sz < fr_block_sz)
{
error("File write failed on server.\n");
}
bzero(revbuf, LENGTH);
if (fr_block_sz == 0 || fr_block_sz != 512)
{
break;
}
}
if(fr_block_sz < 0)
{
if (errno == EAGAIN)
{
printf("recv() timed out.\n");
}
else
{
fprintf(stderr, "recv() failed due to errno = %d\n", errno);
exit(1);
}
}
printf("Ok received from client!\n");
fclose(fr);
}
}
}
Part of server that receive the text:
char buffer[256];
bzero(buffer,256);
int n = 0;
n = read(nsockfd, buffer, 255);
if (n < 0) error("ERROR reading from socket");
printf("msg: %s\n",buffer);
Need some help with that. Thanks...
In this code in your client:
char buffer[256];
int n;
fgets(buffer,255,stdin);
bzero(buffer,256);
n = write(sockfd,buffer, strlen(buffer));
It looks like you are trying to read the file name from the stdin and send it on the sockfd. But. you zero out the buffer before you send it.
Related
Please guide me why is blocking function recv() not waiting for message from client. Instead it is returning value -1. Please guide me how to resolve this issue.
Server code (partial):
(call to getaddrinfo) // struct addrinfo hints, *res
int sfd = socket(res->ai_family, res->ai_socktype,res->ai_protocol);
if(sfd == -1)
{
printf("Socket creation failed .....");
exit(-3);
}
fcntl(sfd, F_SETFL, ~O_NONBLOCK);
if (setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, &(int){ 1 }, sizeof(int)) < 0)
{
herror("setsockopt(SO_REUSEADDR) failed");
}
bind(sfd,res->ai_addr, res->ai_addrlen);
if(listen(sfd, BACKLOG)!=0)
{
printf("Listen Error");
exit(-4);
}
printf("\n\nListening on port: %s\n\n", argv[1]);
struct sockaddr_storage clientAddr;
socklen_t addrSize = sizeof(clientAddr);
int connFD = accept(sfd,(struct sockaddr*)&clientAddr, &addrSize); // connection successful
char buffer[10] = "Hello!";
write(connFD, buffer, sizeof(buffer)); // message sent to client
buffer[0] = '\0';
int bytesReceived;
if((bytesReceived = recv(sfd, buffer, sizeof(buffer), 0)) == -1) // Problem starts here
{
fprintf(stderr,"Could not retrieve message from client.");
exit(-5);
}
the problem is that you are calling recv on wrong socket (sfd) should be (connFD)
fix:
if((bytesReceived = recv(connFD, buffer, sizeof(buffer), 0)) == -1)
Im using socket to send data to remote. The data payload is ~4kB. Problem is tcp segments sent by tcp so slow (delay ~200-300ms each tcp segments).
I tried with TCP_NODELAY (enabled), TCP_QUICKACK (enabled) and TCP_CORK(disabled) but cannot reduce the delayed time.
Here is my tcpdump, each 4kB data sent is divided into 3 tcp segments:
However, I saw a tcpdump by other application (which communicate with same remote). There is a very small or even no time delay between tcp segments.
Here is my code:
void createServerSocket() {
int serverSockFd = socket(AF_INET6, SOCK_STREAM, IPPROTO_TCP);
std::string address = "fd53:7cb8:383:5::73";
int port = 42519;
if (serverSockFd < 0)
{
printf("Create Server socket fail");
return;
}
struct sockaddr_in6 serverAddress;
(void)memset(&serverAddress, 0, sizeof(sockaddr_in6));
serverAddress.sin6_family = AF_INET6;
serverAddress.sin6_port = htons(port);
int result = inet_pton(AF_INET6, address.c_str(), &serverAddress.sin6_addr);
if (result <= 0)
{
printf("inet_pton() failed portnumber: %d, address: %s \n", port, address.c_str());
return;
}
// setting socket options
int flag = 1;
if(setsockopt(serverSockFd,IPPROTO_TCP,TCP_QUICKACK ,(char *)&flag,sizeof(flag)) == -1)
{
printf("setsockopt TCP_QUICKACK failed for server socket on address %s \n", address.c_str());
}
if(setsockopt(serverSockFd,IPPROTO_TCP,TCP_CORK,(char *)&flag,sizeof(flag)) == -1)
{
printf("setsockopt TCP_CORK failed for server socket on address %s \n", address.c_str());
}
if(setsockopt(serverSockFd,IPPROTO_TCP,TCP_NODELAY,(char *)&flag,sizeof(flag)) == -1)
{
printf("setsockopt TCP_NODELAY failed for server socket on address %s \n", address.c_str());
}
result = bind(serverSockFd, (struct sockaddr*)&serverAddress, sizeof(sockaddr_in6));
if (result != 0)
{
printf("bind() failed portnumber: %d, address: %s \n", port, address.c_str());
return ;
}
result = listen(serverSockFd, 10);
if (result != 0) {
printf("listen() failed portnumber: %d, address: %s \n", port, address.c_str());
return ;
}
acceptConnect(serverSockFd);
}
void acceptConnect(int serverSock)
{
struct sockaddr_in6 clientAddress;
socklen_t len = sizeof(sockaddr_in6);
memset(&clientAddress, 0, sizeof(sockaddr_in6));
const int clientSocket = accept(serverSock, (struct sockaddr*)&clientAddress, &len);
if(clientSocket >= 0) {
char str_addr[INET6_ADDRSTRLEN];
inet_ntop(AF_INET6, &(clientAddress.sin6_addr),
str_addr, sizeof(str_addr));
printf("New connection from: %s:%d ...\n", str_addr, ntohs(clientAddress.sin6_port));
receiveDataFromSocket(clientSocket);
}
}
void receiveDataFromSocket(int socket)
{
int SOCKET_BUFFER_MAX_SIZE = 8*1024;
char buffer[SOCKET_BUFFER_MAX_SIZE];
memset(buffer, '\0', SOCKET_BUFFER_MAX_SIZE);
//Receive data from sock
while (true) {
int dataLen = recv(socket, buffer, SOCKET_BUFFER_MAX_SIZE, 0);
printf("Receive data from socket: %d, msgLength = %d\n", socket, dataLen);
sendDataOverSocket(socket);
}
}
void sendDataOverSocket(int clientSock)
{
int dataLen = 4*1024 + 7;
char *buf = new char[dataLen];
memset(buf, 'a', 4*1024 + 7);
int ret;
ret = send(clientSock, buf, dataLen, 0);
if (ret <= 0) {
printf("ERROR Send message over socket");
return;
}
int error_code;
socklen_t error_code_size = sizeof(sockaddr_in6);
getsockopt(clientSock, SOL_SOCKET, SO_ERROR, &error_code, &error_code_size);
printf("Error code size: %d, error code: %d\n", error_code_size, error_code);
}
Does my socket not setting enough to achive tcpdump in second picture?
I thing you are sending too few data evey time.
trying this , in "void sendDataOverSocket(int clientSock)" function, change the sending buffer:
int dataLen = 4*1024 + 7; ===> to a bigger number.
then try it.
Hi everyone i have a little problem, i supposed to transfer a file from a server( a tcp server with threads to a client). The problems appers at the end of transmision the file is recived by client but it stucks and I can't longer communicate with it.
This is the server
int main(int argc, char *argv[])
{
int socket_desc, client_sock, c;
struct sockaddr_in server, client;
//Create socket
socket_desc = socket(AF_INET, SOCK_STREAM, 0);
if (socket_desc == -1)
{
printf("Could not create socket");
}
puts("Socket created");
//Prepare the sockaddr_in structure
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons(2025);
//Bind
if (bind(socket_desc, (struct sockaddr *) &server, sizeof(server)) < 0)
{
//print the error message
perror("bind failed. Error");
return 1;
}
puts("bind done");
//Listen
listen(socket_desc, 5);
//Accept and incoming connection
puts("Waiting for incoming connections...");
c = sizeof(struct sockaddr_in);
int enable = 1;
//Accept and incoming connection
puts("Waiting for incoming connections...");
c = sizeof(struct sockaddr_in);
pthread_t thread_id;
while ((client_sock = accept(socket_desc,
(struct sockaddr *) &client,
(socklen_t*) &c)))
{
puts("Connection accepted");
if (setsockopt(client_sock,
SOL_SOCKET,
SO_REUSEADDR,
&enable,
sizeof(int)) < 0)
error("setsockopt(SO_REUSEADDR) failed");
if (pthread_create(&thread_id,
NULL,
connection_handler,
(void*) &client_sock) < 0)
{
perror("could not create thread");
return 1;
}
//Now join the thread , so that we dont terminate before the thread
pthread_join(thread_id, NULL);
puts("Handler assigned");
}
if (client_sock < 0)
{
perror("accept failed");
return 1;
}
return 0;
}
void *connection_handler(void *socket_desc)
{
printf("Enter in handler");
//Get the socket descriptor
int sock = *(int*) socket_desc;
send_problemo(sock);
return 0;
}
This is the sending function where I think is the real problem
int send_problemo(int *sock)
{
ssize_t read_return;
char *file_path = "Problems/1.txt";
char buffer[BUFSIZ];
int filefd;
filefd = open(file_path, O_RDONLY);
char end[2] = "1";
if (filefd == -1)
{
perror("open");
exit (EXIT_FAILURE);
}
while (1)
{
read_return = read(filefd, buffer, BUFSIZ);
if (read_return == 0)
{
printf("este 0 \n");
break;
}
if (read_return == -1)
{
perror("read");
exit (EXIT_FAILURE);
}
if (write(sock, buffer, read_return) == -1)
{
perror("write");
exit (EXIT_FAILURE);
}
}
// close(sock);
close(filefd);
}
The client is connecting normally and receives the file in this function
int recive_problemo(int *sockfd)
{
char *file_path = "path.c";
char buffer[BUFSIZ];
ssize_t read_return;
int filefd;
filefd = open(file_path, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
if (filefd == -1)
{
perror("open");
exit (EXIT_FAILURE);
}
do
{
read_return = read(sockfd, buffer, BUFSIZ);
if (read_return == -1)
{
perror("read");
exit (EXIT_FAILURE);
}
if (write(filefd, buffer, read_return) == -1)
{
perror("write");
exit (EXIT_FAILURE);
}
} while (read_return > 0);
close(filefd);
}
I kind of managed how to solve this. If i shutdown(SHUT_WR) from server the client isnt stuck anymore, but i want to communicate with it further.
Also with the same function if i transfer from client to server, it works perfectly, so can anyone help me please?
do
{
read_return = read(sockfd, buffer, BUFSIZ);
// error handling
// file write
} while (read_return > 0);
Will keep looping until the socket closes or there's an error. It has no way to tell if a file has finished.
Common solutions are to close the socket (but you don't want that) and establish a communication protocol so that you know when the file is done and can exit the loop.
To keep things very simple, I recommend sending the length of the file before sending the file. The loop now looks something like:
uint64_t file_len;
read_return = recv(sockfd, &file_len, sizeof(file_len), MSG_WAITALL);
if (read_return == sizeof(file_len))
{
// Strongly consider handling the endian of file_len here
while (file_len)
{
size_t readmax = std::min(file_len, BUFSIZ);
read_return = read(sockfd, buffer, readmax);
if (read_return > 0)
{
if (write(filefd, buffer, read_return) == -1)
{
perror("write");
exit (EXIT_FAILURE);
}
file_len -= read_return;
}
else
{
// handle error
// exit loop if not recoverable
}
}
}
The server end picks up the responsibility of getting and sending the length of the file. I won't get into that because there are too many different ways to get the length of a file. Pick your favourite.
Documentation on recv and MSG_WAITALL.
Why when run the program and send data to server return this errorrecv failed: Transport endpoint is not connected or don't show server accepted just show the message of send data function in client
server.cpp:
int main() {
char packet[30];
char buffer[20] = "I got your message";
int conn_sock, comm_sock, n, m;
struct sockaddr_in server_addr, client_addr;
if ((conn_sock = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("Couldn't create socket");
exit(1);
}
cout << "Already create socket!!!\n" << endl;
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(0);
server_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
memset(&server_addr, 0, sizeof(server_addr));
if (bind(conn_sock, (struct sockaddr *) &server_addr, sizeof(server_addr))
== -1) {
perror("couldn't bind");
exit(1);
}
if (listen(conn_sock, 10) == -1) {
perror("couldn't listen");
exit(1);
}
cout << "Listening For Connection...\r" << endl;
socklen_t len = sizeof(server_addr);
if (getsockname(conn_sock, (struct sockaddr *) &server_addr, &len) == -1)
perror("getsockname");
else
printf("port number %d\n", ntohs(server_addr.sin_port));
while (1) {
memset(&client_addr, 0, sizeof(client_addr));
if ((comm_sock = accept(conn_sock, (struct sockaddr *) &client_addr,
(socklen_t *) &client_addr)) == -1) {
perror("couldn't accept\n");
continue;
}
cout << "accepted" << endl;
bzero(packet, 10);
m = recv(conn_sock, packet, 10, 0);
if (m < 0) {
perror("recv failed");
exit(1);
}
cout<<"recieved"<<endl;
/* Write a response to the client */
n = send(conn_sock, buffer, sizeof(buffer), 0);
if (n < 0) {
perror("ERROR send to client");
exit(1);
}
close(n);
close(m);
close(comm_sock);
}
close(conn_sock);
return 0;
}
cilent.cpp:
#define MYPORT 51833
namespace personalization {
bool client::conn() {
//create socket if it is not already created
if (sock == -1) {
//Create socket
sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock == -1) {
perror("Could not create socket");
}
cout << "Socket created" << endl;
}
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(MYPORT);
server_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
if (connect(sock , (struct sockaddr *)&server_addr , sizeof(server_addr)) < 0)
{
perror("connect failed. Error");
return false;
}
cout<<"Connected\n";
return true;
close(sock);
}
bool client::send_data() {
//Send some data
if( send(sock , packet , sizeof( packet ) , 0) < 0)
{
perror("Send failed");
return false;
}
cout<<"Data send\n";
return true;
close(sock);
}
bool client::rec_data() {
char buffer[20];
string reply;
//Receive a echo from the server
if (recv(sock, buffer, sizeof(buffer), 0) < 0) {
perror("receive failed");
return false;
}
reply = buffer;
return true;
close(sock);
}
client::client() {
// TODO Auto-generated constructor stub
sock=-1;
}
output is:
server:Already create socket!!!
Listening For Connection...
port number 51833
client: Socket created
Connected
Data send
receive failed: Connection reset by peer
or:
server:Already create socket!!!
Listening For Connection...
port number 51833
client:Socket created
Connected
Data send
srver:accepted
recv failed: Transport endpoint is not connected
In the server's recv and send calls, you need to pass the socket returned from accept.
So instead of
m = recv(conn_sock, packet, 10, 0);
do
m = recv(comm_sock, packet, 10, 0);
Same goes for the send call.
Also, don't call close on n and m, that is to say remove these two lines of code:
close(n);
close(m);
EDIT: Sorry, while I'm at it, this is probably not what you intended in the client's send_data and rec_data:
return true;
close(sock);
I've wrote a simple client code in python, and I'm trying to connect to a simple echo server written in C.
I know it shouldn't matter, but for some reason I did manage to connect to a server written in python, but I cannot connect to the C server.
Here's the code of the client:
import socket
import sys
import time
HOST = 'localhost'
PORT = 11000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
msg = raw_input()
s.send(msg)
data = s.recv(len(msg))
s.close()
print 'Received: ', data
And here's the C code of the echo server:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <netinet/in.h>
#include <string.h>
#include <netdb.h>
#ifndef AF_INET
#define AF_INET 2
#endif
#ifndef SOCK_DGRAM
#define SOCK_DGRAM 2
#endif
#ifndef INADDR_ANY
#define INADDR_ANY 0
#endif
#ifndef IP_DONTFRAG
#define IP_DONTFRAG 67
#endif
#define BUFFER_SIZE 1024
#define ECHO_PORT_UDP 10000
#define ECHO_PORT_TCP 11000
int main(int argc, char *argv[]) {
int echo_socket = 0;
int echo_socket_child = 0; // for TCP
struct sockaddr_in server;
struct sockaddr_in client;
struct hostent *hostp; // client host info
struct sockaddr_in clientaddr; // client addr
char *hostaddrp; // dotted decimal host addr string
char buffer[BUFFER_SIZE];
unsigned int clientlen = 0;
unsigned int serverlen = 0;
int received = 0;
int port = 0;
char *endptr;
int optval = 1;
int msg_byte_size = 0;
// Parameters check
if (argc == 2) {
port = strtol(argv[1], &endptr, 0);
if ((*endptr) || ((port != ECHO_PORT_UDP) && (port != ECHO_PORT_TCP))) {
printf("EchoServer: Invalid port number.\n Use port %d for UDP, port %d for TCP.\n", ECHO_PORT_UDP, ECHO_PORT_TCP);
return -1;
}
else {
if (port == ECHO_PORT_UDP) {
printf("EchoServer: Running UDP on port %d.\n", port);
}
if (port == ECHO_PORT_TCP) {
printf("EchoServer: Running TCP on port %d.\n", port);
}
}
}
else {
printf("EchoServer: Invalid arguments.\n");
return -1;
}
// Opening UDP socket
if (port == ECHO_PORT_UDP) {
if ((echo_socket = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
printf("EchoServer: Failed opening socket");
return -1;
}
}
if (port == ECHO_PORT_TCP) {
if ((echo_socket = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
printf("EchoServer: Failed opening socket");
return -1;
}
// setsockopt: Handy debugging trick that lets us rerun the server immediately after we kill it; otherwise we have to wait about 20 secs.
// Eliminates "ERROR on binding: Address already in use" error.
setsockopt(echo_socket, SOL_SOCKET, SO_REUSEADDR,(const void *)&optval , sizeof(int));
}
// Construct the server sockaddr_in structure
memset(&server, 0, sizeof(server)); /* Clear struct */
server.sin_family = AF_INET; /* Internet/IP */
server.sin_addr.s_addr = htonl(INADDR_ANY); /* Any IP address */
server.sin_port = htons(atol(argv[1])); /* server port */
// Bind the socket
serverlen = sizeof(server);
if (bind(echo_socket, (struct sockaddr *) &server, serverlen) < 0) {
printf("EchoServer: Failed binding socket");
return -1;
}
// Wait for a datagram until cancelled
if (port == ECHO_PORT_UDP) {
while (1) {
/* Receive a message from the client */
clientlen = sizeof(client);
if ((received = recvfrom(echo_socket, buffer, BUFFER_SIZE, 0, (struct sockaddr *)&client, &clientlen)) < 0) {
printf("EchoServer: Failed receiving datagram");
return -1;
}
printf("Client datagram received from: %s\n", inet_ntoa(client.sin_addr));
/* Send the message back to client */
if (sendto(echo_socket, buffer, received, 0, (struct sockaddr *) &client, sizeof(client)) != received) {
printf("Mismatch in number of echoed bytes");
return -1;
}
}
}
// Wait for a connection until cancelled
if (port == ECHO_PORT_TCP) {
while (1) {
echo_socket_child = accept(echo_socket, (struct sockaddr *) &client, &clientlen);
if (echo_socket_child < 0) {
printf("ERROR on accept");
break;
}
// gethostbyaddr: determine who sent the message
hostp = gethostbyaddr((const char *)&clientaddr.sin_addr.s_addr, sizeof(clientaddr.sin_addr.s_addr), AF_INET);
if (hostp == NULL) {
printf("ERROR on gethostbyaddr");
break;
}
hostaddrp = inet_ntoa(clientaddr.sin_addr);
if (hostaddrp == NULL) {
printf("ERROR on inet_ntoa\n");
break;
}
printf("server established connection with %s \n", hostaddrp);
// read: read input string from the client
bzero(buffer, BUFFER_SIZE);
msg_byte_size = read(echo_socket_child, buffer, BUFFER_SIZE);
if (msg_byte_size < 0) {
printf("ERROR reading from socket");
break;
}
printf("server received %d bytes: %s", msg_byte_size, buffer);
// write: echo the input string back to the client
msg_byte_size = write(echo_socket_child, buffer, strlen(buffer));
if (msg_byte_size < 0) {
printf("ERROR writing to socket");
break;
}
} // endof while(1)
close(echo_socket_child);
return -1;
}
return 0;
}
Any ideas why I fail to connect to the server?
edit:
this is the error I receive:
Traceback (most recent call last):
File "s.py", line 8, in <module>
s.connect((HOST, PORT))
File "C:\Python27\lib\socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 10061]
(1) Add a listen call to the TCP section of the code.
(2) You have to tell accept what the length of the sockaddr you are passing it is and it will in return tell you the length of the address of the client it returned. You were passing it as 0 length so naturally it didn't pass back a client address which subsequently makes your gethostbyaddr fail with unknown address.
(3) If you don't close the client socket within the loop it just remains open (and leaks a file descriptor) for the duration of the server's life. Eventually you will run out of FDs. It doesn't effect your client which just closes after the receipt of one msg but any client who writes more than one message will never have it received by the server and will never receive an eof from the server.
if (port == ECHO_PORT_TCP)
{
if (listen(echo_socket, ECHO_PORT_TCP) == -1)
{
perror("listen");
exit(1);
}
while (1)
{
clientlen = sizeof(client);
echo_socket_child = accept(echo_socket, (struct sockaddr *) &client, &clientlen);
if (echo_socket_child < 0)
{
perror("accept");
break;
}
// gethostbyaddr: determine who sent the message
hostp = gethostbyaddr((const char *) &client.sin_addr.s_addr, sizeof(client.sin_addr.s_addr), AF_INET);
if (hostp == NULL)
{ herror("byaddr");
break;
}
hostaddrp = inet_ntoa(client.sin_addr);
if (hostaddrp == NULL)
{
printf("ERROR on inet_ntoa\n");
break;
}
printf("server established connection with %s (%s)\n", hostp->h_name, hostaddrp);
bzero(buffer, BUFFER_SIZE);
msg_byte_size = read(echo_socket_child, buffer, BUFFER_SIZE);
if (msg_byte_size < 0)
{
printf("ERROR reading from socket");
break;
}
printf("server received %d bytes: %s", msg_byte_size, buffer);
msg_byte_size = write(echo_socket_child, buffer, strlen(buffer));
if (msg_byte_size < 0)
{
printf("ERROR writing to socket");
break;
}
close(echo_socket_child);
} // endof while(1)
return -1;
}