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`
Related
I am new to windows socket programming. I have a device which gives udp data through a port, ipv6 protocol based. I am trying to capture this in a console application written in visual studio in Windows 7. Socket creation and bind are successful but nothing is recieved from the port specified.
I have done this in Linux since i am basically a linux system software developer and it is working perfect. Is there anything else i need to do to get UDP packets in windows. I have checked with wireshark in windows and found that the UDP packets are coming from the device to the PC.
Working Code Done in Linux:
int main()
{
struct sockaddr_in6 ipv6_addr;
int addrlen, ipv6_sockfd, cnt, err;
char response[200], cmd[500];
cJSON *param, *root;
memset(response, 0, sizeof(response));
ipv6_sockfd = socket(AF_INET6, SOCK_DGRAM, IPPROTO_UDP);
if (ipv6_sockfd < 0) {
perror("socket");
exit(1);
}
bzero((char *)&ipv6_addr, sizeof(ipv6_addr));
ipv6_addr.sin6_family = AF_INET6;
ipv6_addr.sin6_addr = in6addr_any;
ipv6_addr.sin6_port = htons(DISCOVERY_PORT);
addrlen = sizeof(ipv6_addr);
if (bind(ipv6_sockfd, (struct sockaddr *)&ipv6_addr, sizeof(ipv6_addr)) < 0) {
perror("bind");
exit(1);
}
cnt = recvfrom(ipv6_sockfd, response, sizeof(response), 0, (struct sockaddr *)&ipv6_addr, &addrlen);
if (cnt < 0) {
perror("recvfrom");
exit(1);
}
DBG("Response = \"%s\"\n", response);
close(ipv6_sockfd);
}
Code in Windows:
#include "stdafx.h"
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdio.h>
#define DISCOVERY_PORT 13006
#define DEFAULT_BUFLEN 512
#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_in6 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_INET6, SOCK_DGRAM, IPPROTO_UDP);
if (s == INVALID_SOCKET)
{
printf("\nUDP socket creation failed ERROR CODE : %d\n", WSAGetLastError());
closesocket(s);
WSACleanup();
return 1;
}
//UDP socket definition
memset(&hum, 0, sizeof(addr));
hum.sin6_family = AF_INET6;
hum.sin6_addr = in6addr_any;
hum.sin6_port = htons(DISCOVERY_PORT);
//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 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("\nMessage: %s\n", message);
return 0;
}
I've implemented a client-server connection over the udp protocol (for handling mouse and keyboard input from smartphone), the only difference is that I used ipv4 instead. Same thing - it perfectly worked on linux, but on windows I didn't see any incoming packet.
The thing that worked to me was to run the program as Administrator and also manually add it to firewall's permissions. In general this wasn't stable on some windows PC's, but after installing my server part program to C:\Program Files it has started to work more or less ok.
Am writing an application for a Point of Sale TERMINAL , the manual for the terminal restricts direct MYSQL connection from the terminal, All connections should be done using Sockets. How can I connect to a MYSQL database using C sockets? Below is my working C program that establishes a TCP connection to specified ip and port.
/*
* Create a TCP socket
* #Author Salim Said
* Jan 2 2015 17:00hrs
*/
#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.235.20");
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 successfully");
return 0;
}
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);
I'm a newbie in Network Programming, started to learn how to use WinSock in C.
I don't have any knowledge in Networking right now.
Anyway, I've written the following code for Client and Server, using WinSock.
Server:
#include <stdio.h>
#include <stdlib.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#define MY_ERROR 1
#define PORT 7777
#define MAX_NUM_CLIENTS 1 /* I don't know how to thread right now. */
#define MAX_CLIENT_MSG_LEN 1000
int main()
{
WSADATA wsa;
SOCKET mySocket, acceptSocket;
struct sockaddr_in server, client;
int sockAddrInLength = sizeof(struct sockaddr_in);
char clientMessage[MAX_CLIENT_MSG_LEN];
int clientMessageLength;
char* message;
int running = 1;
if(WSAStartup(MAKEWORD(2,2), &wsa) != 0)
{
fprintf(stderr, "WSAStartup failed.\n");
return MY_ERROR;
}
printf("WSAStartup succeded.\n");
mySocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (mySocket == INVALID_SOCKET)
{
fprintf(stderr, "Socket creation failed.\n");
return MY_ERROR;
}
printf("Socket creation succeeded.\n");
server.sin_addr.s_addr = INADDR_ANY;
server.sin_family = AF_INET;
server.sin_port = htons(PORT);
if (bind(mySocket, (struct sockaddr*) &server, sizeof server) == SOCKET_ERROR)
{
fprintf(stderr, "Binding socket on port %d failed.\n", PORT);
return MY_ERROR;
}
printf("Binding socket on port %d successfully.\n", PORT);
while (running)
{
listen(mySocket, MAX_NUM_CLIENTS);
printf("Waiting for a connection...\n");
acceptSocket = accept(mySocket, (struct sockaddr*) &client, &sockAddrInLength);
if (acceptSocket == INVALID_SOCKET)
{
fprintf(stderr, "Accept failed.\n");
return MY_ERROR;
}
printf("Accept succeeded.\n");
if ((clientMessageLength = recv(acceptSocket, clientMessage, sizeof clientMessage, 0)) == SOCKET_ERROR)
{
fprintf(stderr, "Recv failed.\n");
return MY_ERROR;
}
printf("Recv succeeded.\n");
printf("Data:\n");
clientMessage[clientMessageLength] = NULL; /* Null terminator */
printf("Client: %s\n", clientMessage);
message = "Hello client, I'm the server. Bye bye. :-)\n";
if (send(acceptSocket, message, strlen(message), 0) < 0)
{
fprintf(stderr, "Send failed.\n");
return MY_ERROR;
}
printf("Send succeded.\n");
}
closesocket(mySocket);
WSACleanup();
getchar();
return 0;
}
And this is the code for the Client:
#include <stdio.h>
#include <stdlib.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#define IP /* My IP */
#define MY_ERROR 1
#define PORT 7777
#define MAX_SERVER_MSG_LEN 1000
int main()
{
WSADATA wsa;
SOCKET mySocket;
struct sockaddr_in server;
char* message;
char serverMessage[MAX_SERVER_MSG_LEN];
int serverMessageLength;
if(WSAStartup(MAKEWORD(2,2), &wsa) != 0)
{
fprintf(stderr, "WSAStartup failed.\n");
getchar();
return MY_ERROR;
}
printf("WSASucceeded.\n");
mySocket = socket(AF_INET,SOCK_STREAM, IPPROTO_TCP);
if (mySocket == INVALID_SOCKET)
{
fprintf(stderr, "Socket creation failed.\n");
getchar();
return MY_ERROR;
}
server.sin_addr.s_addr = inet_addr(IP);
server.sin_family = AF_INET;
server.sin_port = htons(PORT);
if (connect(mySocket, (struct sockaddr*) &server, sizeof server) < 0)
{
fprintf(stderr, "Connection failed. error: %s\n",WSAGetLastError());
getchar();
return MY_ERROR;
}
printf("Connection established.\n");
message = "Hello server, I'm the sweet client. :-)\n";
if (send(mySocket, message, strlen(message), 0) < 0)
{
fprintf(stderr, "Sending failed.\n");
return MY_ERROR;
}
printf("Sending succeeded.\n");
if ((serverMessageLength = recv(mySocket, serverMessage, sizeof serverMessage, 0)) == SOCKET_ERROR)
{
fprintf(stderr, "Recv failed.\n");
return MY_ERROR;
}
printf("Recv succeeded.\n");
printf("Data:\n");
serverMessage[serverMessageLength] = NULL;
printf("Server: %s", serverMessage);
closesocket(mySocket);
getchar();
return 0;
}
Ok.
When I run both server and client on my comupter, and define IP (in the client code) to be my internal IP (I think, becuase it is the form of 192.168.x.x) it works fine.
When I define IP to be my external IP, it doesn't work on my computer (when I run both program in my computer). The connection failes.
In addition -
When I'm trying to run the client on any other computer, it doesn't work (when IP is defined to be my internal or my external IP), the connection failes.
My questions are:
Why when I run both server & client on my computer, it works just with my internal IP?
What should I do in order that the client could be run on another computer and it will work?
I know that maybe the answer contains terms like "internal/external IPs", "routers", maybe "firewall" or "port forwarding".
Just remember I'm really a newbie in Networking and I don't have any knowledge about those terms, so please: I hope your explnations will be beginner-friendly.
I want to start learning Networking, but my first step is to understand how to use Sockets, and I have a problem in the connetction with other computers.
If you have any articles/something like that in order to give me a better understanding of the problem, it could help too.
Thank you very much! :)
This doesn't look like a coding problem, but a network configuration problem.
Let me try and rephrase what you're saying : Please correct me if I've misunderstood:-
You have an "internal" network (192.168.x.y).
You run the client on one PC on your internal network, and the server on another.
It all works so far.
But, you're also connected to the internet, via a different 'external' IP address
- When your client tries to access the server via this address, it fails. (The exact error code from WSAGetLastError is useful here, please)
At this point, it's down to how you're connected to the net. Let's assume a typical home office scenario. You have broadband, with an ADSL router/modem giving you network connectivity. Now, while the router will have an 'external' IP address, PC's on your local network typically do NOT. So, if you try connecting to the 'external' IP, you're actually trying to talk to the router.
This is where Port forwarding comes into play. You need to configure the router to forward port 7777 to the correct IP address for your server on the internal network. You'll find a screen like this on your router somewhere.
You would enter port 7777 for both 'from' and 'to', enable TCP, and specify the LAN address of your server. The router will then forward incoming connections on port 7777 to the specified server.
I'm trying to program a simple client and server using sockets in C. Both the client and server are running Ubuntu. The server is broadcasting an ad-hoc network that the however I cannot seem to get the client to connect to the server despite being able to ping it from terminal.
The code I'm using for the server and client are adapted from an online source and are as such:
#include<stdio.h>
#include<string.h> //strlen
#include<sys/socket.h>
#include<arpa/inet.h> //inet_addr
#include<unistd.h> //write
int main(int argc , char *argv[])
{
int socket_desc , new_socket , c;
struct sockaddr_in server , client;
char *message;
//Create socket
socket_desc = socket(AF_INET , SOCK_STREAM , 0);
if (socket_desc == -1)
{
printf("Could not create socket");
}
//Prepare the sockaddr_in structure
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons( 8888 );
//Bind
if( bind(socket_desc,(struct sockaddr *)&server , sizeof(server)) < 0)
{
puts("bind failed");
return 1;
}
puts("bind done");
//Listen
listen(socket_desc , 3);
//Accept and incoming connection
puts("Waiting for incoming connections...");
c = sizeof(struct sockaddr_in);
new_socket = accept(socket_desc, (struct sockaddr *)&client, (socklen_t*)&c);
if (new_socket<0)
{
perror("accept failed");
return 1;
}
puts("Connection accepted");
//Reply to the client
message = "Hello Client , I have received your connection. But I have to go now, bye\n";
write(new_socket , message , strlen(message));
return 0;
}
Client
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
int main(int argc , char *argv[])
{
int socket_desc;
struct sockaddr_in server;
char *message;
//Create socket
socket_desc = socket(AF_INET , SOCK_STREAM , 0);
if (socket_desc == -1)
{
printf("Could not create socket");
}
server.sin_addr.s_addr = inet_addr("192.168.0.1");
server.sin_family = AF_INET;
server.sin_port = htons( 80 );
//Connect to remote server
if (connect(socket_desc , (struct sockaddr *)&server , sizeof(server)) < 0)
{
puts("connect error");
return 1;
}
puts("Connected\n");
//Send some data
message = "GET / HTTP/1.1\r\n\r\n";
if( send(socket_desc , message , strlen(message) , 0) < 0)
{
puts("Send failed");
return 1;
}
puts("Data Send\n");
return 0;
}
The IP address was obtained by running ifconfig on the terminal of the server and looking at its inet addr value.
Additionally I've also disabled the firewall on both the client and the server by running sudo ufw disable in the terminal. Errno also outputs connection refused.
Can anyone please help me with this?
Your server listens to port 8888 and client tries to connect to port 80, both server.sin_port = htons( x ); must use the same port number.
Instead of directly using inet_addr("192.168.0.1");
use
struct sockaddr_in6 ser_address;
inet_pton(AF_INET,"192.168.0.1",&ser_address.sin.addr);
Note: We cannot use presentation style address in the codes when passing it to socket functions