mattias1975
Programmer
I have made a socket program that is supposed to
receive some text from a client.
But there is something wrong when i call the
listen function. It returns -1.
Does anyone know whats wrong?
Mattias Westerberg
#include <winsock2.h>
#include <iostream.h>
#define BACKLOG 10
void main()
{
WORD wVersionRequested;
WSADATA wsaData;
int err;
wVersionRequested = MAKEWORD( 2, 2 );
err = WSAStartup( wVersionRequested, &wsaData );
if ( err != 0 )
cout << "could not find a usable WinSock DLL" << "\n";
if ( LOBYTE( wsaData.wVersion ) != 2 || HIBYTE( wsaData.wVersion ) != 2 ) {
WSACleanup( );
cout << "could not find a usable WinSock DLL" << "\n";
}
int sockfd, new_fd;
struct sockaddr_in my_addr;
struct sockaddr_in their_addr;
int sin_size;
if ((sockfd = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP)) == -1) {
cout << "socket";
exit(1);
}
my_addr.sin_family = AF_INET;
my_addr.sin_addr.s_addr = inet_addr("xxx.xxx.x.x");
my_addr.sin_port = htons(321);
memset(&(my_addr.sin_zero), '\0', 8);
if (bind(sockfd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr)) == -1) {
cout << "bind";
exit(1);
}
if (listen(sockfd, BACKLOG) == -1) {
cout << "listen";
exit(1);
}
char buf[100];
int numbytes;
while(1) {
sin_size = sizeof(struct sockaddr_in);
if ((new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size)) == -1) {
cout << "accept";
continue;
}
if ((numbytes=recv(sockfd, buf, 100, 0)) != -1) {
cout << buf;
break;
}
}
}
receive some text from a client.
But there is something wrong when i call the
listen function. It returns -1.
Does anyone know whats wrong?
Mattias Westerberg
#include <winsock2.h>
#include <iostream.h>
#define BACKLOG 10
void main()
{
WORD wVersionRequested;
WSADATA wsaData;
int err;
wVersionRequested = MAKEWORD( 2, 2 );
err = WSAStartup( wVersionRequested, &wsaData );
if ( err != 0 )
cout << "could not find a usable WinSock DLL" << "\n";
if ( LOBYTE( wsaData.wVersion ) != 2 || HIBYTE( wsaData.wVersion ) != 2 ) {
WSACleanup( );
cout << "could not find a usable WinSock DLL" << "\n";
}
int sockfd, new_fd;
struct sockaddr_in my_addr;
struct sockaddr_in their_addr;
int sin_size;
if ((sockfd = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP)) == -1) {
cout << "socket";
exit(1);
}
my_addr.sin_family = AF_INET;
my_addr.sin_addr.s_addr = inet_addr("xxx.xxx.x.x");
my_addr.sin_port = htons(321);
memset(&(my_addr.sin_zero), '\0', 8);
if (bind(sockfd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr)) == -1) {
cout << "bind";
exit(1);
}
if (listen(sockfd, BACKLOG) == -1) {
cout << "listen";
exit(1);
}
char buf[100];
int numbytes;
while(1) {
sin_size = sizeof(struct sockaddr_in);
if ((new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size)) == -1) {
cout << "accept";
continue;
}
if ((numbytes=recv(sockfd, buf, 100, 0)) != -1) {
cout << buf;
break;
}
}
}