I am working in a simple socket project. I would like to know:
why error messages appear before telnet localhost 5678?
why SO_REUSEADDR (between socket() and bind()) don't work, and what else I should try?
Code Output Message:
bind error
Error opening file: Address already in use
telnet localhost 5678
[+]Server Socket is created.
main.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <errno.h>
#define BUFSIZE 1024 // Buffer Size
#define PORT 5678
int main() {
printf("telnet localhost 5678\n");
int rfd; // socket descriptor
int clientfd; // client descriptor
struct sockaddr_in client; // Client Socket address
socklen_t client_len; // Length of Client Data
char input[BUFSIZE]; // Client Data -> Server
int bytes_read; // Client Bytes
// 1. socket() = create a socket, SOCK_STREAM = TCP
rfd = socket(AF_INET, SOCK_STREAM, 0);
if (rfd < 0) {
fprintf(stderr, "socket error\n");
exit(-1);
}
printf("[+]Server Socket is created.\n");
// optional
int enable = 1;
if (setsockopt(rfd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int)) < 0)
fprintf(stderr, "setsockopt(SO_REUSEADDR) failed");
//Initialize the server address by the port and IP
struct sockaddr_in server;
memset(&server, 0, sizeof(server));
server.sin_family = AF_INET; // Internet address family: v4 address
server.sin_addr.s_addr = INADDR_ANY; // Server IP address
server.sin_port = htons(PORT); // Server port
// 2. bind() = bind the socket to an address
int brt = bind(rfd, (struct sockaddr *) &server, sizeof(server));
if (brt < 0) {
int errnum;
errnum = errno;
fprintf(stderr, "bind error\n");
fprintf(stderr, "Error opening file: %s\n", strerror(errnum));
exit(-1);
}
printf("[+]Bind to port %d\n", PORT);
// 3. listen() = listen for connections
int lrt = listen(rfd, 50);
if (lrt < 0) {
printf("listen error\n");
exit(-1);
}
if (lrt == 0) {
printf("[+]Listening....\n");
}
// non-stop loop
while (1) {
// 4. accept() = accept a new connection on socket from client
clientfd = accept(rfd, (struct sockaddr *) &client, &client_len);
if (clientfd < 0) {
fprintf(stderr, "accept failed with error %d\n");
exit(-1);
}
printf("Client connected\n");
...
close(clientfd);
printf("Client disconnected\n");
}
close(rfd);
}
I'm assuming that you are using Linux. If you want to rebind to an address, you should use SO_REUSEPORT not SO_REUSEADDR. Name is really misleading. But make sure that you know how it works and whether you really want to use it or not.
You can check difference here: How do SO_REUSEADDR and SO_REUSEPORT differ?
I'm new to socket programming and this is my first server-client program. The program was working perfectly fine at first, but when I copied my code from Server.c and Client.c to a new project in Visual Studio, my client is now refusing to connect and throws the error 10049. I can still connect to my server if I use telnet from command prompt.
I am surprised as to why my client would stop working when I copy the code to another empty project, nothing else has changed.
I have tried changing IP addresses, port numbers and port forwarding using my public address to no avail. I have confirmed my computer's IP using ipconfig and it is correctly inputted in my code, as well as the port number. The program compiles fine with no errors whatsoever.
Server.c
#include <winsock2.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <WS2tcpip.h>
#pragma comment (lib, "Ws2_32.lib")
void start_server(const char* ip_address, int port_number);
int server_sock, client_sock;
void main(int argc, char* argv[])
{
start_server("192.168.0.24", 100);
system("pause");
}
void start_server(const char* ip_address, int port_number)
{
WSADATA wsaData;
int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != NO_ERROR) {
wprintf(L"WSAStartup() failed with error: %d\n", iResult);
return 1;
}
struct sockaddr_in server_addr;
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(port_number);
InetPton(AF_INET, "", &server_addr.sin_addr.s_addr);
server_sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (server_sock == INVALID_SOCKET)
{
printf(L"Socket creation failed with error: %ld\n", WSAGetLastError());
}
else
{
printf("Socket created!\n");
}
int bind_status = bind(server_sock, (struct sockaddr*) & server_addr, sizeof(server_addr));
if (bind_status == SOCKET_ERROR) {
wprintf(L"bind failed with error: %ld\n", WSAGetLastError());
}
else
{
printf("Bind was successful!\n");
}
int listen_status = listen(server_sock, 3);
if (listen_status == -1)
{
wprintf(L"listen failed with error: %ld\n", WSAGetLastError());
}
else
{
printf("Listening...\n");
}
client_sock = accept(server_sock, NULL, NULL);
if (client_sock == -1)
{
wprintf(L"client socket failed with error: %ld\n", WSAGetLastError());
}
else
{
printf("Accepted new client!\n");
}
}
Client.c
#include <winsock2.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <WS2tcpip.h>
#pragma comment (lib, "Ws2_32.lib")
void connect_server(const char* ip_address, int port_number);
int sock;
void main()
{
connect_server("192.168.0.24", 100);
send(sock, "test", 5, 0);
system("pause");
}
void connect_server(const char* ip_address, int port_number)
{
WSADATA wsaData;
int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != NO_ERROR) {
wprintf("WSAStartup() failed with error: %d\n", iResult);
exit(1);
}
struct sockaddr_in server_addr;
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(port_number);
InetPton(AF_INET, ip_address, &server_addr.sin_addr.s_addr);
sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sock == INVALID_SOCKET)
{
printf("Socket creation failed with error: %d\n", WSAGetLastError());
}
else
{
printf("Socket created!\n");
}
int connection_status = connect(sock, (struct sockaddr *) &server_addr, sizeof(server_addr));
if (connection_status == SOCKET_ERROR)
{
printf("Connection failed with error: %d\n", WSAGetLastError());
}
else
{
printf("Connected.\n");
}
}
A very fast/simple search for WSA error 10049 results in:
Winsock error 10049 typically occurs when you attempt to create a socket with an address not on this machine. For example if you have MDaemon running on a machine with an IP address of 192.168.0.1 and you attempt to bind MDaemon to 192.168.0.100 you will receive this error message.
So, you need to correct the IP address for the new computer.
Try using your code with loopback address 127.0.0.1. If it works then definitely problem is with the combination of IP and Port number. Maybe use ipconfig /reset to reset your ip address.
Hai friends I am a newbie learning winsock2. the following is my udp server and client programs.
I this program the client does not know the ip address of the server but knows only the port. But the server broadcasts a message all over the network.
when the client gets the message it traces back the ip of the server and connects to it.
Both my server and client show no error while compiling.
But while Executing the client's recvfrom() statement shows error
the following are the part of my code.
SERVER CODE:
#include "stdafx.h"
#include<stdio.h>
#include<WinSock2.h>
#pragma comment (lib,"ws2_32.lib")
DWORD WINAPI UDPCONN(LPVOID x)
{
SOCKET s=(SOCKET)x;
char bro[200]="I am SERVER";
struct sockaddr_in hum;
hum.sin_family=AF_INET;
hum.sin_addr.s_addr=INADDR_BROADCAST;
hum.sin_port=htons(8888);
while (1)
{
if(sendto(s,bro,sizeof(bro),0,(struct sockaddr *)&hum,sizeof(hum))==SOCKET_ERROR)
{
printf("\nBroadcast failed ERROR CODE : %d\n",WSAGetLastError());
exit(1);
}
}
}
int _tmain(int argc, _TCHAR* argv[])
{
SOCKET s;
struct sockaddr_in hum;
int opt=1;
//Initializing winsock2
WSADATA wsa;
if((WSAStartup(MAKEWORD(2,2),&wsa))!=0)
{
printf("\nWinsock Not initialized ERROR CODE : %d\n",WSAGetLastError());
return 1;
}
//UDP Socket Creation
if((s=socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP))==INVALID_SOCKET)
{
printf("\nUDP Socket not created ERROR CODE : %d\n",WSAGetLastError());
WSACleanup();
return 1;
}
//socket defenition
hum.sin_family=AF_INET;
hum.sin_addr.s_addr=INADDR_ANY;
hum.sin_port=htons(8888);
//Broadcast permission
if((setsockopt(s,SOL_SOCKET,SO_BROADCAST,(char *)&opt,sizeof(opt)))<0)
{
printf("\nBroadcast permissions failed ERROR CODE : %d\n",WSAGetLastError());
WSACleanup();
return 1;
}
//UDP SOCKET Binding
if((bind(s,(sockaddr *)&hum,sizeof(hum)))==SOCKET_ERROR)
{
printf("\nUDP socket binding failed ERROR CODE :%d\n",WSAGetLastError());
WSACleanup();
return 1;
}
//UDP connection thread
DWORD th;
CreateThread(NULL,0,UDPCONN,(LPVOID)s,0,&th);
CLIENT CODE :
#include "stdafx.h"
#include <stdio.h>
#include <WinSock2.h>
#pragma comment(lib,"ws2_32.lib")
int _tmain(int argc, _TCHAR* argv[])
{
//UDP Data
int slen;
char message[300];
int opt=1;
SOCKET s;
struct sockaddr_in sent;
//Initializing winsock
WSADATA wsa;
if((WSAStartup(MAKEWORD(2,2),&wsa))!=0)
{
printf("\nFailed Initializing Winsock EROR CODE : %d\n",WSAGetLastError());
return 1;
}
//UDP Socket creation
if((s=socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP))== SOCKET_ERROR)
{
printf("\nUDP socket creation failed ERROR CODE :%d\n",WSAGetLastError());
WSACleanup();
return 1;
}
//UDP Broadcast permissions
if((setsockopt(s,SOL_SOCKET,SO_BROADCAST,(char *)&opt,sizeof(opt)))<0)
{
printf("\nERROR in broadcasting ERROR CODE : %d \n",WSAGetLastError());
WSACleanup();
return 1;
}
//UDP socket definition
sent.sin_family=AF_INET;
sent.sin_addr.s_addr=INADDR_ANY;
sent.sin_port=htons(8888);
//UDP Receiving broadcasted data
slen=sizeof(sent);
//fflush(stdout);
memset(message,'\0',300);
if((recvfrom(s,message,sizeof(message),0,(struct sockaddr *)&sent,&slen))<0)
{
printf("\nUDP Broadcast not received ERROR CODE : %d\n",WSAGetLastError());
WSACleanup();
return 1;
}
puts("\nGot server broadcast\n");
puts("\nTracing server ip\n");
getpeername(s,(sockaddr *)&sent,&slen);
...
}
Here my client throw an error
UDP Broadcast not received ERROR CODE : 10022
Description of the error code 10022 : Invalid argument.
Some invalid argument was supplied (for example, specifying an invalid level to the setsockopt function). In some instances, it also refers to the current state of the socket—for instance, calling accept on a socket that is not listening.
According to the error description one of the arguments in the recvfrom() function is invalid. But i could not find out the invalid argument .
Please help me clear the error.
If you read the recvfrom() documentation, it tells you exactly why you are getting the error in your client code:
Parameters
s [in]
A descriptor identifying a bound socket.
...
WSAEINVAL
The socket has not been bound with bind, or an unknown flag was specified, or MSG_OOB was specified for a socket with SO_OOBINLINE enabled, or (for byte stream-style sockets only) len was zero or negative.
You are not calling bind() on the socket before calling recvfrom(). More importantly, you cannot bind() the client and server to the same IP/port when they are running on the same machine. Change the port that you broadcast to, and then have the client bind to that port.
Also, the last two parameters of recvfrom() provide you with the IP/Port of the datagram sender. They are not for specifying the network adapter to read datagrams on. You do not need to use getpeername() in this situation.
There are some other issues with your code:
On the client side, socket() returns INVALID_SOCKET on failure, not SOCKET_ERROR.
On the server side, you really should not be using INADDR_BROADCAST. You should bind() the server socket to a specific network adapter and then sendto() its particular subnet broadcast IP, which you can calculate using GetAdaptersInfo() or GetAdaptersAddresses().
And on both sides, you cannot use WSAGetLastError() if WSAStartup() fails, that is why WSAStartup() returns the error code directly. And you are not closing the sockets before calling WSACleanup();
Try this:
SERVER CODE:
#include "stdafx.h"
#include <stdio.h>
#include <WinSock2.h>
#pragma comment (lib,"ws2_32.lib")
DWORD WINAPI UDPCONN(LPVOID x)
{
SOCKET s = (SOCKET)x;
char bro[200] = "I am SERVER";
struct sockaddr_in hum;
memset(&hum, 0, sizeof(addr));
hum.sin_family = AF_INET;
hum.sin_addr.s_addr = INADDR_BROADCAST; // TODO: replace with subnet broadcast IP
hum.sin_port = htons(8887);
while (1)
{
if (sendto(s, bro, sizeof(bro), 0, (struct sockaddr *)&hum, sizeof(hum)) == SOCKET_ERROR)
{
printf("\nBroadcast failed ERROR CODE : %d\n", WSAGetLastError());
return 1;
}
}
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
SOCKET s;
struct sockaddr_in hum;
int err, opt=1;
//Initializing winsock2
WSADATA wsa;
err = WSAStartup(MAKEWORD(2,2), &wsa);
if (err != 0)
{
printf("\nWinsock Not initialized ERROR CODE : %d\n", err);
return 1;
}
//UDP Socket Creation
s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (s == INVALID_SOCKET)
{
printf("\nUDP Socket not created ERROR CODE : %d\n", WSAGetLastError());
WSACleanup();
return 1;
}
//socket defenition
memset(&hum, 0, sizeof(hum));
hum.sin_family = AF_INET;
hum.sin_addr.s_addr = INADDR_ANY; // TODO: replace with a specific NIC IP
hum.sin_port = htons(8888);
//Broadcast permission
if (setsockopt(s, SOL_SOCKET, SO_BROADCAST, (char *)&opt, sizeof(opt)) == SOCKET_ERROR)
{
printf("\nBroadcast permissions failed ERROR CODE : %d\n", WSAGetLastError());
closesocket(s);
WSACleanup();
return 1;
}
//UDP SOCKET Binding
if (bind(s, (sockaddr *)&hum, sizeof(hum)) == SOCKET_ERROR)
{
printf("\nUDP socket binding failed ERROR CODE : %d\n", WSAGetLastError());
closesocket(s);
WSACleanup();
return 1;
}
//UDP connection thread
DWORD th;
HANDLE hThread = CreateThread(NULL,0, UDPCONN, s, 0, &th);
if (!hThread)
{
printf("\nUDP thread failed ERROR CODE : %u\n", GetLastError());
closesocket(s);
WSACleanup();
return 1;
}
// do other things, wait for thread to terminate ...
DWORD exitCode = 0;
GetExitCodeThread(hThread, &exitCode);
CloseHandle(hThread);
closesocket(s);
WSACleanup();
return exitCode;
}
CLIENT CODE :
#include "stdafx.h"
#include <stdio.h>
#include <WinSock2.h>
#pragma comment(lib,"ws2_32.lib")
int _tmain(int argc, _TCHAR* argv[])
{
//UDP Data
int addrlen, msglen;
char message[300];
int err, opt=1;
SOCKET s;
struct sockaddr_in hum, addr;
//Initializing winsock
WSADATA wsa;
err = WSAStartup(MAKEWORD(2,2), &wsa);
if (err != 0)
{
printf("\nFailed Initializing Winsock EROR CODE : %d\n", err);
return 1;
}
//UDP Socket creation
s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (s == INVALID_SOCKET)
{
printf("\nUDP socket creation failed ERROR CODE : %d\n", WSAGetLastError());
closesocket(s);
WSACleanup();
return 1;
}
//UDP Broadcast permissions
if (setsockopt(s, SOL_SOCKET, SO_BROADCAST, (char *)&opt, sizeof(opt)) == SOCKET_ERROR)
{
printf("\nERROR in broadcasting ERROR CODE : %d \n", WSAGetLastError());
closesocket(s);
WSACleanup();
return 1;
}
//UDP socket definition
memset(&hum, 0, sizeof(addr));
hum.sin_family = AF_INET;
hum.sin_addr.s_addr = INADDR_ANY;
hum.sin_port = htons(8887);
//UDP SOCKET Binding
if (bind(s, (sockaddr *)&hum, sizeof(hum)) == SOCKET_ERROR)
{
printf("\nUDP socket binding failed ERROR CODE : %d\n", WSAGetLastError());
closesocket(s);
WSACleanup();
return 1;
}
//UDP Receiving broadcasted data
addrlen = sizeof(addr);
msglen = recvfrom(s, message, sizeof(message), 0, (struct sockaddr *)&addr, &addrlen);
if (msglen == SOCKET_ERROR)
{
printf("\nUDP Broadcast not received ERROR CODE : %d\n", WSAGetLastError());
closesocket(s);
WSACleanup();
return 1;
}
printf("\nGot server broadcast\n");
printf("\nServer ip: %s, port: %hu\n", inet_ntoa(addr.sin_addr), ntohs(addr.sin_port));
printf("\nMessage: %.*s\n", msglen, message);
...
}
Whatever method i tried sending a broadcast from server and receiving the broadcast from client is not working efficiently.
Instead i done the reverse i.e send a broadcast from client to search for the server is working perfectly.
Here is my modified code.
SERVER CODE:
#include "stdafx.h"
#include<stdio.h>
#include<WinSock2.h>
#pragma comment (lib,"ws2_32.lib")
DWORD WINAPI UDPCONN(LPVOID x)
{
SOCKET s=(SOCKET)x;
struct sockaddr_in server;
int len;
char buf[500]=("I am server");
char message[500];
len=sizeof(server);
int opt=1;
if((s=socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP))==INVALID_SOCKET)
{
printf("\nSocket creation failed. ERROR CODE : %d\n",WSAGetLastError());
WSACleanup();
ExitThread(NULL);
}
server.sin_family=AF_INET;
server.sin_addr.s_addr=INADDR_ANY;
server.sin_port=htons(8888);
if(setsockopt(s,SOL_SOCKET,SO_BROADCAST,(char *)&opt,sizeof(opt))<0)
{
printf("\nSetting broadcast failed : %d\n",WSAGetLastError());
WSACleanup();
ExitThread(NULL);
}
if((bind(s,(sockaddr *)&server,sizeof(server)))==SOCKET_ERROR)
{
printf("\nBind failed. ERROR CODE : %d\n",WSAGetLastError());
WSACleanup();
ExitThread(NULL);
}
while(1)
{
fflush(stdout);
memset(message,'\0', 500);
//try to receive some data, this is a blocking call
if (recvfrom(s, message, 500, 0, (struct sockaddr *) &server,&len) == SOCKET_ERROR)
{
printf("recvfrom() failed with error code : %d" , WSAGetLastError());
ExitThread(NULL);
}
if(sendto(s,buf,sizeof(buf),0,(struct sockaddr *)&server,sizeof(server))==SOCKET_ERROR)
{
printf("\nIP Broadcast failed ERROR code : %d\n",WSAGetLastError());
WSACleanup();
ExitThread(NULL);
}
}
}
int _tmain(int argc, _TCHAR* argv[])
{
SOCKET s;
//struct sockaddr_in hum;
int opt=1;
//Initializing winsock2
WSADATA wsa;
if((WSAStartup(MAKEWORD(2,2),&wsa))!=0)
{
printf("\nWinsock Not initialized ERROR CODE : %d\n",WSAGetLastError());
return 1;
}
s=socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
//UDP connection thread
DWORD th;
CreateThread(NULL,0,UDPCONN,(LPVOID)s,0,&th);
closesocket(s);
CLIENT CODE :
#include "stdafx.h"
#include <stdio.h>
#include <WinSock2.h>
#pragma comment(lib,"ws2_32.lib")
int _tmain(int argc, _TCHAR* argv[])
{
//UDP Data
int slen;
char message[600];
char buf[300]=("Hai server");
int opt=1;
SOCKET s;
struct sockaddr_in sent;
//TCP Connection data
SOCKET t;
struct sockaddr_in server;
char messag[300],server_reply[300];
int recv_size;
//Initializing winsock
WSADATA wsa;
if((WSAStartup(MAKEWORD(2,2),&wsa))!=0)
{
printf("\nFailed Initializing Winsock EROR CODE : %d\n",WSAGetLastError());
return 1;
}
//UDP Socket creation
if((s=socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP))== INVALID_SOCKET)
{
printf("\nUDP socket creation failed ERROR CODE :%d\n",WSAGetLastError());
WSACleanup();
return 1;
}
//UDP Broadcast permissions
if((setsockopt(s,SOL_SOCKET,SO_BROADCAST,(char *)&opt,sizeof(opt)))<0)
{
printf("\nERROR in broadcasting ERROR CODE : %d \n",WSAGetLastError());
WSACleanup();
return 1;
}
//UDP socket definition
sent.sin_family=AF_INET;
sent.sin_addr.s_addr=INADDR_BROADCAST;
sent.sin_port=htons(8888);
if (sendto(s, buf, sizeof(buf) , 0 , (struct sockaddr *) &sent,sizeof(sent)) == SOCKET_ERROR)
{
printf("sendto() failed with error code : %d" , WSAGetLastError());
exit(EXIT_FAILURE);
}
//UDP Receiving broadcasted data
slen=sizeof(sent);
fflush(stdout);
memset(message,'\0',300);
if((recvfrom(s,message,sizeof(message),0,(struct sockaddr *)&sent,&slen))<0)
{
printf("\nUDP Broadcast not received ERROR CODE : %d\n",WSAGetLastError());
WSACleanup();
return 1;
}
puts("\nGot server broadcast\n");
puts("\nTracing server ip\n");
getpeername(s,(sockaddr *)&sent,&slen);
closesocket(s);
Both the codes here works perfectly fine in visual studios 2012.
Also this is just one part of my whole big program. But still this part works perfectly fine independently.
So please make sure you compiled and run the program before posting negative comments.
Hi I'm new to socket programming and I'm trying out the following code from the tutorial of http://www.binarytides.com/winsock-socket-programming-tutorial/
I'm trying to connect to server and I'm using the IP address of google. Here is the code:
#include<stdio.h>
#include<winsock2.h>
#pragma comment(lib,"ws2_32.lib") //Winsock Library
int main(int argc , char *argv[])
{
WSADATA wsa;
SOCKET s;
struct sockaddr_in server;
printf("\nInitialising Winsock...");
if (WSAStartup(MAKEWORD(2,2),&wsa) != 0)
{
printf("Failed. Error Code : %d",WSAGetLastError());
return 1;
}
printf("Initialised.\n");
//Create a socket
if((s = socket(AF_INET , SOCK_STREAM , 0 )) == INVALID_SOCKET)
{
printf("Could not create socket : %d" , WSAGetLastError());
}
printf("Socket created.\n");
server.sin_addr.s_addr = inet_addr("74.125.224.72");
server.sin_family = AF_INET;
server.sin_port = htons(80);
//Connect to remote server
if (connect(s, (struct sockaddr *)&server , sizeof(server)) < 0)
{
puts("connect error");
return 1;
}
puts("Connected");
return 0;
}
So far socket can be created but I can't connect to the server. To be more specific I always exit and have following:
The program '[2060] SocketCTest.exe: Native' has exited with code 1 (0x1).
even if I set a breakpoint before returns.
There's no error. I've tried on my computer and connect returned with error (WSAETIMEDOUT). I'm not sure whether there are the network settings on my computer, proxies, firewalls, and so on; or that google host is configured not to accept direct socket connections.
Anyway here's your code with some small adjustments:
#include <stdio.h>
#include <conio.h>
#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib") //Winsock Library
int main(int argc, char *argv[])
{
WSADATA wsa;
SOCKET s;
struct sockaddr_in server;
char c = 0;
printf("\nInitialising Winsock...");
if (WSAStartup(MAKEWORD(2,2), &wsa) != 0)
{
printf("Failed. Error Code : %d.\nPress a key to exit...", WSAGetLastError());
c = getch();
return 1;
}
printf("Initialised.\n");
//Create a socket
if((s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == INVALID_SOCKET)
{
printf("Could not create socket : %d.\n", WSAGetLastError());
WSACleanup();
c = getch();
return 1;
}
printf("Socket created. Connecting...\n");
memset(&server, 0, sizeof server);
server.sin_addr.s_addr = inet_addr("74.125.224.72");
server.sin_family = AF_INET;
server.sin_port = htons(80);
//Connect to remote server
if (connect(s, (struct sockaddr *)&server, sizeof(server)) < 0)
{
printf("Connect error:%d.\nPress a key to exit...", WSAGetLastError());
closesocket(s);
WSACleanup();
c = getch();
return 1;
}
puts("Connected.\nPress a key to exit...");
closesocket(s);
WSACleanup();
c = getch();
return 0;
}
Now if you want to see the code actually connecting i'd suggest using localhost (127.0.0.1) instead of 74.125.224.72, and the port 3389 for example (it's the Remote Desktop Server (RDP) port, if you have RDP configured and running on your computer) instead of 80; or you could let 80 if you have a web server (IIS?) running on your computer.
To get a list of server programs that run on your computer run the command:
`netstat -an | findstr LISTEN`
which would output a bunch of lines (and the ones that we care about are) in this form (here's the one corresponding to the RDP example from above):
`TCP 127.0.0.1:3389 0.0.0.0:0 LISTENING`
Hi I'm new to socket programming. I'm currently writing c code for client, which is my computer, to send something to local host 127.0.0.1 and see if local host has got the request and anything back. I can already get connected to the local host but I don't know what command do I use to test if I can talk to the local host.
#include<stdio.h>
#include<winsock2.h>
#pragma comment(lib, "ws2_32.lib") //Winsock Library
int main(int argc, char *argv[])
{
WSADATA wsa;
SOCKET s;
struct sockaddr_in server;
char *message , server_reply[2000];
int recv_size;
printf("\nInitialising Winsock...");
if (WSAStartup(MAKEWORD(2,2), &wsa) != 0)
{
printf("Failed. Error Code : %d", WSAGetLastError());
return 1;
}
printf("Initialised.\n");
//Create a socket
if((s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == INVALID_SOCKET)
{
printf("Could not create socket : %d\n", WSAGetLastError());
return 1;
}
printf("Socket created.\n");
//server.sin_addr.s_addr = 127.0.0.1;
//server.sin_addr.s_addr = inet_addr("74.125.224.72"); //google IP address
server.sin_addr.s_addr = inet_addr("127.0.0.1"); //local host IP
server.sin_family = AF_INET;
//server.sin_port = htons(80);//IIS port
server.sin_port = htons(60441); //local port
//server.sin_port = 80;
//Connect to remote server
if (connect(s, (struct sockaddr *)&server, sizeof(server)) < 0)
{
printf("connect error:%d\n", WSAGetLastError());
closesocket(s);
WSACleanup();
system("pause");
return 1;
}
puts("Connected\n");
closesocket(s);
WSACleanup();
system("pause");
return 0;
}
Once you get a connection, you can use send to send a message to the remote server and recv to get a response back. Exactly what you send and what you expect to receive depend entirely on what service you're talking to.
EDIT:
As an example, suppose you're talking to a web server and you want to retrieve the main page. You could do this:
char request[] = "GET / HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n";
size_t bytesSent = send(s, request, strlen(request), 0);
if (bytesSent == -1) {
printf("Error sending: %d\n", WSAGetLastError());
return 1;
}
char response[10000];
memset(response, 0, sizeof(response));
size_t bytesRead = recv(s, response, sizeof(response), 0);
if (bytesRead == -1) {
printf("Error receiving: %d\n", WSAGetLastError());
return 1;
}
printf("response from web server: %.*s\n", bytesRead, response);