I have been working on a packet sniffer just for fun/education and it's been going quite well. The problem that I'm having is that the only packets appearing in recvfrom() are SENT packets i.e. packets with my IP as their source IP and not my WAN IP but my LAN IP (if that makes sense).
I tried fixing it and spent hours reading everything I could find but to me there seems no solution.
I am 100% positive that the code I've written does not detect all packets because wireshark detects way more (ingoing and outgoing) and it's obvious that there is not only outgoing traffic from my PC.
packetsize = recvfrom(sniffer , Buffer , 65536 , 0 , (SOCKADDR *)&SenderAddr , &SenderAddrSize);
for (int x = 12; x < 16; x++)
{
printf("%c ",Buffer[x]);
}
std::cout << "\n";
iphdr = (IPV4_HDR *)Buffer;
memset(&source, 0, sizeof(source));
source.sin_addr.s_addr = iphdr->ip_srcaddr;
std::cout << inet_ntoa(source.sin_addr) << "\n\n";
That's the point where it all goes down (there is way more code but not important), the structures are all properly defined so there is no errors there (else I couldn't be getting the same IP adress over and over in every single packet).
Also there is another, non-existent IP from my network showing up as source IP and very occasionally the source IP is 0.0.0.0 which I both find very weird.
Buffer is declared as
char *Buffer = (char *)malloc(65536);
so it's signed char and I have no idea how I could manually "extract" the separate parts of the header from these values.
I hope anyone can explain to me that recvfrom is actually not losing packets and that I'm doing something wrong.
Also I'd like to know how to interpret the output from recvfrom, i.e. converting signed to unsigned or maybe some other way?
I hope I made my problem clear, thanks in advance.
EDIT. Bigger chunk of my code
int main()
{
SOCKET sniffer;
struct in_addr addr;
int in;
char hostname[100];
struct hostent *local;
WSADATA wsa;
// Initialise Winsock
printf("\nInitialising Winsock...");
if (WSAStartup(MAKEWORD(2,2), &wsa) != 0)
{
printf("WSAStartup() failed.\n");
getchar();
return 1;
}
printf("Initialised");
// Create a RAW Socket
printf("\nCreating RAW Socket....");
sniffer = socket(AF_INET, SOCK_RAW, IPPROTO_IP);
if (sniffer == INVALID_SOCKET)
{
printf("Failed to create raw socket.\n");
printf("WSA throws error code %d\n",WSAGetLastError());
printf("Run as admin to fix\n");
getchar();
return 1;
}
printf("Created.");
// Retrieve the local hostname
if (gethostname(hostname, sizeof(hostname)) == SOCKET_ERROR)
{
printf("WSA throws error code %d\n",WSAGetLastError());
getchar();
return 1;
}
printf("\nHost name : %s \n",hostname);
bool retry = true;
signed int maxnumber = -1;
do
{
// Retrieve the available IPs of the local host
local = gethostbyname(hostname);
printf("\nAvailable Network Interfaces \n");
if (local == NULL)
{
printf("WSA throws error code %d.\n",WSAGetLastError());
getchar();
return 1;
}
// Available interfaces
for (i = 0; local->h_addr_list[i] != 0; i++) // h_addr_list is null terminated
{
// local is hostent struct in which information about the host is stored
// in_addr represents an IPv4 internet address. inet_ntoa: in_addr to string (ip adress)
memmove(&addr, local->h_addr_list[i], sizeof(struct in_addr));
//memmove(destination, source, number of bytes to copy)
printf("Interface Number : %d Address : %s\n", i, inet_ntoa(addr));
maxnumber = i;
printf("\n");
}
// Choose interface
if (maxnumber > 0)
{
printf("Enter the interface number you would like to sniff : ");
scanf("%d",&in);
printf(" in: %d | maxnumber: %d \n", in, maxnumber);
if (in <= maxnumber)
{
retry = false;
} else {
printf("Interface number %d with adress %d does not exist \n\n", in, local->h_addr_list[in]);
}
}
else
{
printf("Only one interface available");
in = 0;
retry = false;
}
} while (retry);
self = addr;
CreateFolder(self);
memset(&dest, 0, sizeof(dest));
memcpy(&dest.sin_addr.s_addr,local->h_addr_list[in],sizeof(dest.sin_addr.s_addr));
dest.sin_family = AF_INET;
dest.sin_port = htons(source.sin_port);//=0;
printf("\nBinding socket to local system and port 0 ...");
if (bind(sniffer,(struct sockaddr *)&dest,sizeof(dest)) == SOCKET_ERROR)
{
printf("bind(%s) failed.\n", inet_ntoa(addr));
getchar();
return 1;
}
printf("Binding successful");
j=1;
unsigned long nbytesret;
printf("\nSetting socket to sniff...");
if (WSAIoctl(sniffer, SIO_RCVALL, &j, sizeof(j), 0, 0, &nbytesret , 0 , 0) == SOCKET_ERROR)
{
printf("WSAIoctl() failed.\n");
getchar();
return 1;
}
printf("Socket set\n");
printf("Press enter to start\n");
getchar();
printf("Packet Capture Statistics...\n");
StartSniffing(sniffer);
printf("Ending sniffer, press enter to exit \n");
getchar();
closesocket(sniffer);
WSACleanup();
return 0;
}
void StartSniffing(SOCKET sniffer)
{
char *Buffer = (char *)malloc(65536);
int packetsize;
if (Buffer == NULL)
{
printf("malloc() failed.\n");
getchar();
return;
}
do
{
packetsize = recvfrom(sniffer , Buffer , 65536 , 0 , (SOCKADDR *)&SenderAddr , &SenderAddrSize);
if(packetsize > 0)
{
ProcessPacket(Buffer, packetsize);
}
else
{
printf( "recvfrom() failed.\n");
getchar();
}
}
while (packetsize > 0);
free(Buffer);
}
To read from the buffer as unsigned, use reinterpret_cast like so to get an unsigned pointer:
unsigned char *uBuffer = reinterpret_cast<unsigned char *>(Buffer);
Related
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.
(English is not my native tongue, don't worry if some sentences are strange ;) ).
I was developing a PONG game and by the way creating some classes to help me managing window, event ... and network because I added a LAN feature to the game but currently you have to enter the address of the one with who you want to play with. And a solution to that was a broadcast (scanning LAN for player). This was easy with ipv4, just use the address 255.255.255.255 but we are in 2017 and provide a feature that works only with ipv4 sucks...
Then I look for a way to broadcast with ipv6 and I learn about multi-cast but this part just get me lost. =(
I use standard libraries on Linux in C++, I found several example of multi-cast that didn't work with me. The best I have done at this time is sending a udp packet from one instance of the program to an other on the same computer.
How can I multi-cast with ipv6 udp socket on Linux in C/C++ ?
The best code found on Internet (I rearranged it) that almost work
(there is client and serv all in one, choice is made by adding 1 or 0 to argv) :
int main(int argc, char const *argv[]) {
struct sockaddr_in6 groupSock;
int sd = -1;
char databuf[10];
int datalen = sizeof databuf;
/* Create a datagram socket on which to send/receive. */
if((sd = socket(AF_INET6, SOCK_DGRAM, 0)) < 0) {
perror("Opening datagram socket error");
return 1;
} else {
cout << "Opening the datagram socket...OK." << endl;;
}
/* Enable SO_REUSEADDR to allow multiple instances of this */
/* application to receive copies of the multicast datagrams. */
int reuse = 1;
if(setsockopt(sd, SOL_SOCKET, SO_REUSEADDR, (char *)&reuse, sizeof reuse) < 0) {
perror("Setting SO_REUSEADDR error");
close(sd);
return 1;
} else {
cout << "Setting SO_REUSEADDR...OK." << endl;
}
/* Initialize the group sockaddr structure with a */
memset((char *) &groupSock, 0, sizeof groupSock);
groupSock.sin6_family = AF_INET6;
// address of the group
inet_pton(AF_INET6, "ff0e::/16", &groupSock.sin6_addr);
groupSock.sin6_port = htons(4321);
/* Set local interface for outbound multicast datagrams. */
/* The IP address specified must be associated with a local, */
/* multicast capable interface. */
int ifindex = if_nametoindex ("enp3s0");
cout << "ifindex is " << ifindex << endl;
if(setsockopt(sd, IPPROTO_IPV6, IPV6_MULTICAST_IF, &ifindex, sizeof ifindex)) {
perror("Setting local interface error");
return 1;
} else {
cout << "Setting the local interface...OK" << endl;
}
// choice is 0 for sending and 1 for receiving
int choice;
if (argc < 2) {
cout << "missing argv[1]" << endl;
return 1;
}
sscanf (argv[1], "%d", &choice);
// if sending
if (choice == 0) {
memset(databuf, 'a', datalen);
databuf[sizeof databuf - 1] = '\0';
if (sendto(sd, databuf, datalen, 0, (sockaddr*)&groupSock, sizeof groupSock) < 0) {
cout << "Error in send" << endl;
} else {
cout << "Send okay!" << endl;
}
}
// if receiving
else if (choice == 1) {
groupSock.sin6_addr = in6addr_any;
if(bind(sd, (sockaddr*)&groupSock, sizeof groupSock)) {
perror("Binding datagram socket error");
close(sd);
return 1;
} else {
cout << "Binding datagram socket...OK." << endl;
}
/* Join the multicast group ff0e::/16 on the local */
/* interface. Note that this IP_ADD_MEMBERSHIP option must be */
/* called for each local interface over which the multicast */
/* datagrams are to be received. */
struct ipv6_mreq group;
inet_pton (AF_INET6, "ff0e::", &group.ipv6mr_multiaddr.s6_addr);
group.ipv6mr_interface = ifindex;
if(setsockopt(sd, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, (char *)&group, sizeof group) < 0) {
perror("Adding multicast group error");
close(sd);
return 1;
} else {
cout << "Adding multicast group...OK." << endl;
}
if (read(sd, databuf, datalen) < 0) {
perror("Error in read");
} else {
databuf[sizeof databuf - 1] = '\0';// just for safety
cout << "Read Okay" << endl;
cout << "Message is : " << databuf << endl;
}
}
return 0;
}
Here the address is ff0e:: but I have try with ff01:: and ff02::.
I need help, I have not found any simple documentation about that. Thanks in advance for any answer.
Edit :
Thanks Ron Maupin and Jeremy Friesner for these comments, it helps me.
Edit :
THANKS Jeremy ! Your advice to use ff12::blah:blah(...) instead of ff0e:: works ! Should I write answer to my question to close the thread ?
This code below is right:
The only thing wrong is the address used for the multicast.
Like Jeremy said it, ff0e:: is not correct, I used instead ff12::feed:a:dead:beef and it works.
It is possible to get the name and index of the available interface by using if_nameindex().
Update : I try to remove some code to see if it work without it and I manage to get this :
server :
// OPEN
int fd = socket(AF_INET6, SOCK_DGRAM, 0);
// BIND
struct sockaddr_in6 address = {AF_INET6, htons(4321)};
bind(fd, (struct sockaddr*)&address, sizeof address);
// JOIN MEMBERSHIP
struct ipv6_mreq group;
group.ipv6mr_interface = 0;
inet_pton(AF_INET6, "ff12::1234", &group.ipv6mr_multiaddr);
setsockopt(fd, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, &group, sizeof group);
// READ
char buffer[128];
read(fd, buffer, sizeof buffer);
client :
// OPEN
int fd = socket(AF_INET6, SOCK_DGRAM, 0);
// ADDRESS
struct sockaddr_in6 address = {AF_INET6, htons(4321)};
inet_pton(AF_INET6, "ff12::1234", &address.sin6_addr);
// SEND TO
char buffer[128];
strcpy(buffer, "hello world!");
sendto(fd, buffer, sizeof buffer, 0, (struct sockaddr*)&address, sizeof address);
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;
}
I am trying to send some data with a udp socket and receive them back on the same socket through windows loopback adatper. In my network properties I set the loopback adapter to have the following ip 192.168.1.1
the recvfrom function returns -1 indicating an error. I also monitor the traffic on the loopback adapter with wireshark and nothing seem to be sent to the loopback adapter, I see no trafic.
Is it true that on windows we can't use the loopback address(127.0.0.1) ? I saw that on some forums, that is why I try to use the loopback adapter.
I also tried to send directly to my own ip, but it gives no better results. Btw it is possible to send to his own ip and get the data back?
I would appreciate any help and just in case, I am new to socket programming.
Below is my code:
#define DST "192.168.1.1"
int _tmain(int argc, char* argv[])
{
int numbytes;
int bytes_sent;
int server_sock;
char send_msg[100];
int send_msg_length = 100;
char rcv_msg[100] = { 0 };
int rcv_msg_length = 100;
int i;
WSADATA wsaData;
if(WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
{
fprintf(stderr, "WSAStartup failed.\n");
return 1;
}
sockaddr_in to_addr;
sockaddr_in me;
unsigned short Port = 27015;
to_addr.sin_family = AF_INET;
to_addr.sin_port = htons(Port);
to_addr.sin_addr.s_addr = inet_addr(DST);
me.sin_family = AF_INET;
me.sin_port = 0;
me.sin_addr.s_addr = htonl(INADDR_ANY);
memset( &(me.sin_zero), '\0', 8 );
if ((server_sock = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
{
perror("talker: socket");
}
if ( bind( server_sock, (SOCKADDR *)&me, sizeof( me ) ) == -1)
{
printf("Error binding/n");
return 1;
};
int length = sizeof( to_addr );
bytes_sent = sendto(server_sock, send_msg, send_msg_length, 0, (SOCKADDR *)&to_addr, length);
if (bytes_sent == -1)
{
perror("talker: sendto");
exit(1);
}
printf("Sent %d bytes to %s\n", bytes_sent, DST);
printf("listener: waiting to recvfrom...\n");
if ( numbytes = recvfrom(server_sock, rcv_msg, rcv_msg_length, 0, (SOCKADDR *)&to_addr, &length ) )
{
perror("recvfrom");
exit(1);
}
closesocket(server_sock);
WSACleanup();
return 0;
}
You are binding your server socket to port 0, i.e. asking the OS to assign random port number to it. That has to be the same port you are sending to, 27015 in your case.
Also, you don't have to byte-swap INADDR_ANY.