Related
when I compile this program and run it, I get the output below. I added the bind failed with error output for debugging and it suggests that with the error code that I received from listen the socket is not bound using bind but the 0 output is confusing me as that is the output when everything worked. I would appreciate any suggestions
#define DefaultBufLen 1024
SOCKET Socket = INVALID_SOCKET;
int difficulty = 0;
WSADATA wsaData;
struct addrinfo* result = NULL,
* ptr = NULL,
hints;
sockaddr_in Service;
int recvbuflen = DefaultBufLen;
char SendBuf[DefaultBufLen] = "";
char RecvBuf[DefaultBufLen] = "";
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != NO_ERROR) {
wprintf(L"Startup failed with error code %d\n", WSAGetLastError());
return 1;
};
Socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (Socket == INVALID_SOCKET) {
wprintf(L"Socket failed with error: %1d\n", WSAGetLastError());
WSACleanup();
return 1;
};
Service.sin_family = AF_INET;
Service.sin_addr.s_addr = inet_addr("127.0.0.1");
Service.sin_port = htons(27015);
bind(Socket, (SOCKADDR*)&Service, sizeof(Service));
wprintf(L"bind failed with error: %ld\n", WSAGetLastError());
while (1) {
if (listen(Socket, 2000) == SOCKET_ERROR) {
wprintf(L"listen failed with error: %ld\n", WSAGetLastError());
closesocket(Socket);
WSACleanup();
return 1;
}
else {
wprintf(L"listen succeeded!\n");
}
SOCKET AcceptingSocket;
wprintf(L"Waiting for client to connect...\n");
AcceptingSocket = accept(Socket, NULL, NULL);
if (AcceptingSocket == INVALID_SOCKET) {
wprintf(L"accept failed with error: %ld\n", WSAGetLastError());
closesocket(Socket);
WSACleanup();
return 1;
}
else {
wprintf(L"Client connected.\n");
}
int Error = 0;
do {
Error = recv(Socket, RecvBuf, recvbuflen, 0);
if (Error > 0)
printf("Bytes received: %d\n", Error);
else if (Error == 0)
printf("Connection closed\n");
else
printf("recv failed: %d\n", WSAGetLastError());
} while (Error > 0);
string TranslatedRecvBuf = RecvBuf;
vector<string> Request;
boost::split(Request, TranslatedRecvBuf, boost::is_any_of(";"));
if (Request[0] == "RBlock") {
Irrelevant
else if (Request[0] == "DBlock") {
Irrelevant
else if (Request[0] == "TxIncl") {
Irrelevant
else if (Request[0] == "BaLook") {
Irrelevant
closesocket(AcceptingSocket);
};
};
Output:
bind failed with error: 0
listen failed with error: 10022
[process exited with code 1 (0x00000001)]
I have maybe a strange problem, but I can't get sockets working. I need to connect c++ app with node.js server, which has open socket. I have tried many sources, but none of them are working. One of that, that I have at the moment:
#define DEFAULT_BUFLEN 512
#define DEFAULT_PORT "3000"
int sock()
{
int argc = 2;
const char* argv[3];
argv[0] = "127.0.0.1";
argv[1] = "127.0.0.1";
WSADATA wsaData;
SOCKET ConnectSocket = INVALID_SOCKET;
struct addrinfo* result = NULL,
* ptr = NULL,
hints;
const char* sendbuf = "this is a test";
char recvbuf[DEFAULT_BUFLEN];
int iResult;
int recvbuflen = DEFAULT_BUFLEN;
// Validate the parameters
if (argc != 2) {
printf("usage: %s server-name\n", argv[0]);
return 1;
}
// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != 0) {
printf("WSAStartup failed with error: %d\n", iResult);
return 1;
}
ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
// Resolve the server address and port
iResult = getaddrinfo(argv[1], DEFAULT_PORT, &hints, &result);
if (iResult != 0) {
printf("getaddrinfo failed with error: %d\n", iResult);
WSACleanup();
return 1;
}
// Attempt to connect to an address until one succeeds
for (ptr = result; ptr != NULL; ptr = ptr->ai_next) {
// Create a SOCKET for connecting to server
ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype,
ptr->ai_protocol);
if (ConnectSocket == INVALID_SOCKET) {
printf("socket failed with error: %ld\n", WSAGetLastError());
WSACleanup();
return 1;
}
// Connect to server.
iResult = connect(ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen);
if (iResult == SOCKET_ERROR) {
closesocket(ConnectSocket);
ConnectSocket = INVALID_SOCKET;
continue;
}
break;
}
freeaddrinfo(result);
if (ConnectSocket == INVALID_SOCKET) {
printf("Unable to connect to server!\n");
WSACleanup();
return 1;
}
// Send an initial buffer
iResult = send(ConnectSocket, sendbuf, (int)strlen(sendbuf), 0);
if (iResult == SOCKET_ERROR) {
printf("send failed with error: %d\n", WSAGetLastError());
closesocket(ConnectSocket);
WSACleanup();
return 1;
}
printf("Bytes Sent: %ld\n", iResult);
// shutdown the connection since no more data will be sent
iResult = shutdown(ConnectSocket, SD_SEND);
if (iResult == SOCKET_ERROR) {
printf("shutdown failed with error: %d\n", WSAGetLastError());
closesocket(ConnectSocket);
WSACleanup();
return 1;
}
// Receive until the peer closes the connection
do {
iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);
if (iResult > 0)
printf("Bytes received: %d\n", iResult);
else if (iResult == 0)
printf("Connection closed\n");
else
printf("recv failed with error: %d\n", WSAGetLastError());
} while (iResult > 0);
// cleanup
closesocket(ConnectSocket);
WSACleanup();
return 0;
}
This is official microsoft code for the winsock client. Also, I have tried socket client code from here: https://www.geeksforgeeks.org/socket-programming-cc/
From the microsoft code I am getting that, data was sent, but node.js console remains empty: https://prnt.sc/zdhpsi
Node.js server code:
var port = 3000;
var io = require('socket.io')().listen(port);
console.log("Listening on port " + port);
/* Socket.IO events */
io.on("connection", function(socket){
console.log("new connection");
socket.on('test_text', (...args) => {
console.log("test text event received.", args);
});
socket.on('test_binary', (...args) => {
console.log("test binary event received", args);
if(args[0] instanceof Buffer)
{
console.log("test binary event received,binary length:"+ args[0].length);
}
});
socket.on('test ack',function()
{
var args =Array.prototype.slice.call(arguments);
if('object' == typeof args[0])
{
console.log("test combo received,object:");
console.log(JSON.stringify(args[0]));
}
if(args.length>1 && 'function' == typeof args[args.length - 1])
{
console.log('need ack for test combo');
var fn = args[args.length - 1];
fn('Got bin length:' + args[0].bin.length);//invoke ack callback function.
}
});
});
On c++ side I don't need to recieve anything, I just need to send the data
Maybe you know how this could be done? Thanks :)
#define PORT 3000
int sock()
{
int valread;
struct sockaddr_in serv_addr;
const char* hello = "Hello from client";
char buffer[1024] = { 0 };
SOCKET sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock < 0)
{
printf("\n Socket creation error \n");
return -1;
}
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(PORT);
// Convert IPv4 and IPv6 addresses from text to binary form
if (inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr) <= 0)
{
printf("\nInvalid address/ Address not supported \n");
return -1;
}
if (connect(sock, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) < 0)
{
printf("\nConnection Failed \n");
return -1;
}
send(sock, hello, strlen(hello), 0);
printf("Hello message sent\n");
return 0;
}
I have this code for the sockets, to be sent at localhost:3000 address. But they are not sent, and Connection failed error pops up. I have node.js server listener socket open at that port.
On Windows only 1, you must call WSAStartup() to initialize the Winsock library before using any other socket functions, like connect(). See Initializing Winsock. And you should call WSACleanup() when you are done using Winsock.
1: On non-Windows platforms, there are no equivalent startup/cleanup functions that need to be called when using sockets.
Try something more like this:
#include <winsock2.h>
#include <windows.h>
#include <stdio.h>
#define PORT 3000
int main()
{
WSADATA wsa;
int iResult = WSAStartup(MAKEWORD(2,0), &wsa);
if (iResult != 0)
{
printf("WSAStartup failed: %d\n", iResult);
return INVALID_SOCKET;
}
printf("Winsock initialized\n");
struct sockaddr_in serv_addr;
ZeroMemory(&serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(PORT);
// Convert IPv4 and IPv6 addresses from text to binary form
if (inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr) <= 0)
{
printf("Invalid address/ Address not supported \n");
WSACleanup();
return -1;
}
SOCKET sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sock == INVALID_SOCKET)
{
printf("Socket creation failed: %d\n", WSAGetLastError());
WSACleanup();
return -1;
}
if (connect(sock, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) == SOCKET_ERROR)
{
printf("Connection failed: %d\n", WSAGetLastError());
closesocket(sock);
WSACleanup();
return -1;
}
printf("Connection successful\n");
const char* hello = "Hello from client";
if (send(sock, hello, strlen(hello), 0) == SOCKET_ERROR)
{
printf("Send failed: %d\n", WSAGetLastError());
closesocket(sock);
WSACleanup();
return -1;
}
printf("Hello message sent\n");
closesocket(sock);
WSACleanup();
return 0;
}
That said, you really should be using getaddrinfo() instead of inet_pton(), especially if you want to support both IPv4 and IPv6, eg:
#include <winsock2.h>
#include <ws2tcpip.h>
#include <windows.h>
#include <stdio.h>
#define PORT "3000"
int main()
{
WSADATA wsa;
int iResult = WSAStartup(MAKEWORD(2,0), &wsa);
if (iResult != 0)
{
printf("WSAStartup failed: %d\n", iResult);
return INVALID_SOCKET;
}
printf("Winsock initialized\n");
struct addrinfo hints, *addrs;
ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
// Convert IPv4 and IPv6 addresses from text to binary form
iResult = getaddrinfo("127.0.0.1", PORT, &hints, &addrs);
if (iResult != 0)
{
printf("Get Address Info failed: (%d) %s\n", iResult, gai_strerror(iResult));
WSACleanup();
return -1;
}
SOCKET sock = INVALID_SOCKET;
for(struct addrinfo *addr = addrs; addr != NULL; addr = addr->ai_next)
{
sock = socket(addr->ai_family, addr->ai_socktype, addr->ai_protocol);
if (sock != INVALID_SOCKET)
{
if (connect(sock, addr->ai_addr, addr->ai_addrlen) != SOCKET_ERROR)
break;
closesocket(sock);
sock = INVALID_SOCKET;
}
}
if (sock == INVALID_SOCKET)
{
printf("Socket creation failed/Connection failed\n");
WSACleanup();
return -1;
}
printf("Connection successful\n");
const char* hello = "Hello from client";
if (send(sock, hello, strlen(hello), 0) == SOCKET_ERROR)
{
printf("Send failed: %d\n", WSAGetLastError());
closesocket(sock);
WSACleanup();
return -1;
}
printf("Hello message sent\n");
closesocket(sock);
WSACleanup();
return 0;
}
I'm now facing the problem of C++ winsock server programming for receiving messages from both TCP and UDP. In fact, UDP is used for receiving the job message from another server, while TCP receives messages from multiple RFID receivers.
So I've googled for days to see what approach I can use, and I found the followings:
https://msdn.microsoft.com/en-us/library/windows/desktop/ms738620(v=vs.85).aspx
http://www.masterraghu.com/subjects/np/introduction/unix_network_programming_v1.3/ch08lev1sec15.html
However, I still cannot come up with the clear flow that how I can start the server application without selecting either TCP or UDP by the command line arguement i.e. I just want to start the winsock server program with creating both TCP and UDP sockets and then wait for connections.
So, according to the above two links, how can I do for the purpose I stated above i.e. how can I initialize the TCP and UDP sockets when I start the program and then go into the while loop for waiting the connections? Thanks!
Edited 20150918 4:12pm HKT
I've tried to combine the examples in two links provided above, but it is work for TCP while not in UDP. What is the problem for UDP according to the following server and client codes? Thanks!
server.cpp
#define WIN32_LEAN_AND_MEAN
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#define _CRT_SECURE_NO_WARNINGS
#include <windows.h>
#include <winsock2.h>
#include <Ws2tcpip.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <algorithm>
// Link with ws2_32.lib
#pragma comment(lib, "Ws2_32.lib")
#define STRICMP _stricmp
#define DEFAULT_PORT 5001
#define DEFAULT_PROTO SOCK_STREAM // TCP
void Usage(char *progname) {
fprintf(stderr, "Usage\n%s -e [endpoint] -i [interface]\n",
progname);
fprintf(stderr, "Where:\n\tendpoint is the port to listen on\n");
fprintf(stderr, "\tinterface is the ipaddr (in dotted decimal notation)");
fprintf(stderr, " to bind to\n");
fprintf(stderr, "Defaults are 5001 and INADDR_ANY\n");
WSACleanup();
exit(1);
}
int main(int argc, char **argv) {
char Buffer[128];
char *interface = NULL;
unsigned short port = DEFAULT_PORT;
int retval;
int fromlen;
int i;
int maxfdp1, nready;
struct sockaddr_in local, from;
WSADATA wsaData;
SOCKET listen_socket, udp_socket, msgsock;
fd_set SockSet;
/* Parse arguments */
if (argc >1) {
for (i = 1; i <argc; i++) {
if ((argv[i][0] == '-') || (argv[i][0] == '/')) {
switch (tolower(argv[i][1])) {
case 'i':
interface = argv[++i];
break;
case 'e':
port = (unsigned short)atoi(argv[++i]);
break;
default:
Usage(argv[0]);
break;
}
}
else
Usage(argv[0]);
}
}
if ((retval = WSAStartup(0x202, &wsaData)) != 0) {
fprintf(stderr, "WSAStartup failed with error %d\n", retval);
WSACleanup();
return -1;
}
if (port == 0){
Usage(argv[0]);
}
local.sin_family = AF_INET;
local.sin_addr.s_addr = (!interface) ? INADDR_ANY : inet_addr(interface);
/*
* Port MUST be in Network Byte Order
*/
local.sin_port = htons(port);
listen_socket = socket(AF_INET, SOCK_STREAM, 0); // TCP socket
if (listen_socket == INVALID_SOCKET){
fprintf(stderr, "socket() failed with error %d\n", WSAGetLastError());
WSACleanup();
return -1;
}
if (bind(listen_socket, (struct sockaddr*)&local, sizeof(local))
== SOCKET_ERROR) {
fprintf(stderr, "TCP bind() failed with error %d\n", WSAGetLastError());
WSACleanup();
return -1;
}
if (listen(listen_socket, 5) == SOCKET_ERROR) {
fprintf(stderr, "TCP listen() failed with error %d\n", WSAGetLastError());
WSACleanup();
return -1;
}
else
printf("TCP listen() established\n");
udp_socket = socket(AF_INET, SOCK_DGRAM, 0);
if (bind(udp_socket, (struct sockaddr*)&local, sizeof(local))
== SOCKET_ERROR) {
fprintf(stderr, "UDP bind() failed with error %d\n", WSAGetLastError());
WSACleanup();
return -1;
}
else
printf("UDP bind() established\n");
FD_ZERO(&SockSet);
maxfdp1 = max(listen_socket, udp_socket) + 1;
while (1) {
fromlen = sizeof(from);
FD_SET(listen_socket, &SockSet);
FD_SET(udp_socket, &SockSet);
if ((nready = select(maxfdp1, &SockSet, NULL, NULL, NULL)) < 0)
fprintf(stderr, "select() failed with error %d\n", WSAGetLastError());
if (FD_ISSET(listen_socket, &SockSet))
{
msgsock = accept(listen_socket, (struct sockaddr*)&from, &fromlen);
if (msgsock == INVALID_SOCKET)
{
fprintf(stderr, "accept() error %d\n", WSAGetLastError());
WSACleanup();
return -1;
}
else
printf("TCP msgsock=%d listen_socket=%d\n", msgsock, listen_socket);
printf("accepted connection from %s, port %d\n",
inet_ntoa(from.sin_addr),
htons(from.sin_port));
retval = recv(msgsock, Buffer, sizeof(Buffer), 0);
if (retval == SOCKET_ERROR) {
fprintf(stderr, "recv() failed: error %d\n", WSAGetLastError());
closesocket(msgsock);
continue;
}
if (retval == 0) {
printf("Client closed connection\n");
closesocket(msgsock);
continue;
}
printf("Received %d bytes, data [%s] from client\n", retval, Buffer);
printf("Echoing same data back to client\n");
retval = send(msgsock, Buffer, sizeof(Buffer), 0);
if (retval == SOCKET_ERROR) {
fprintf(stderr, "send() failed: error %d\n", WSAGetLastError());
}
printf("Terminating connection\n");
closesocket(msgsock);
}
else if (FD_ISSET(udp_socket, &SockSet))
{
retval = recvfrom(msgsock, Buffer, sizeof(Buffer), 0,
(struct sockaddr *)&from, &fromlen);
printf("Received datagram from %s\n", inet_ntoa(from.sin_addr));
if (retval == SOCKET_ERROR) {
fprintf(stderr, "recv() failed: error %d\n", WSAGetLastError());
closesocket(msgsock);
continue;
}
if (retval == 0) {
printf("Client closed connection\n");
closesocket(msgsock);
continue;
}
printf("Received %d bytes, data [%s] from client\n", retval, Buffer);
printf("Echoing same data back to client\n");
retval = sendto(msgsock, Buffer, sizeof(Buffer), 0,
(struct sockaddr *)&from, fromlen);
if (retval == SOCKET_ERROR) {
fprintf(stderr, "send() failed: error %d\n", WSAGetLastError());
}
printf("UDP server looping back for more requests\n");
}
continue;
}
}
client.cpp
#ifndef UNICODE
#define UNICODE
#endif
#define WIN32_LEAN_AND_MEAN
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#include <winsock2.h>
#include <Ws2tcpip.h>
#include <stdio.h>
#include <stdlib.h>
// Link with ws2_32.lib
#pragma comment(lib, "Ws2_32.lib")
#define DEFAULT_PORT 5001
#define DEFAULT_PROTO SOCK_STREAM // TCP
void Usage(char *progname) {
fprintf(stderr, "Usage\n%s -p [protocol] -n [server] -e [endpoint] \
-l [iterations]\n",
progname);
fprintf(stderr, "Where:\n\tprotocol is one of TCP or UDP\n");
fprintf(stderr, "\tserver is the IP address or name of server\n");
fprintf(stderr, "\tendpoint is the port to listen on\n");
fprintf(stderr, "\titerations is the number of loops to execute\n");
fprintf(stderr, "\t(-l by itself makes client run in an infinite loop,");
fprintf(stderr, " Hit Ctrl-C to terminate it)\n");
fprintf(stderr, "Defaults are TCP , localhost and 5001\n");
WSACleanup();
exit(1);
}
int main(int argc, char **argv) {
char Buffer[128];
char *server_name = "localhost";
unsigned short port = DEFAULT_PORT;
int retval, loopflag = 0;
int i, loopcount, maxloop = -1;
unsigned int addr;
int socket_type = DEFAULT_PROTO;
struct sockaddr_in server;
struct hostent *hp;
WSADATA wsaData;
SOCKET conn_socket;
if (argc >1) {
for (i = 1; i <argc; i++) {
if ((argv[i][0] == '-') || (argv[i][0] == '/')) {
switch (tolower(argv[i][1])) {
case 'p':
if (!_stricmp(argv[i + 1], "TCP"))
socket_type = SOCK_STREAM;
else if (!_stricmp(argv[i + 1], "UDP"))
socket_type = SOCK_DGRAM;
else
Usage(argv[0]);
i++;
break;
case 'n':
server_name = argv[++i];
break;
case 'e':
port = (USHORT)atoi(argv[++i]);
break;
case 'l':
loopflag = 1;
if (argv[i + 1]) {
if (argv[i + 1][0] != '-')
maxloop = atoi(argv[i + 1]);
}
else
maxloop = -1;
i++;
break;
default:
Usage(argv[0]);
break;
}
}
else
Usage(argv[0]);
}
}
if ((retval = WSAStartup(0x202, &wsaData)) != 0) {
fprintf(stderr, "WSAStartup failed with error %d\n", retval);
WSACleanup();
return -1;
}
if (port == 0){
Usage(argv[0]);
}
//
// Attempt to detect if we should call gethostbyname() or
// gethostbyaddr()
if (isalpha(server_name[0])) { /* server address is a name */
hp = gethostbyname(server_name);
}
else { /* Convert nnn.nnn address to a usable one */
addr = inet_addr(server_name);
hp = gethostbyaddr((char *)&addr, 4, AF_INET);
}
if (hp == NULL) {
fprintf(stderr, "Client: Cannot resolve address [%s]: Error %d\n",
server_name, WSAGetLastError());
WSACleanup();
exit(1);
}
//
// Copy the resolved information into the sockaddr_in structure
//
memset(&server, 0, sizeof(server));
memcpy(&(server.sin_addr), hp->h_addr, hp->h_length);
server.sin_family = hp->h_addrtype;
server.sin_port = htons(port);
conn_socket = socket(AF_INET, socket_type, 0); /* Open a socket */
if (conn_socket <0) {
fprintf(stderr, "Client: Error Opening socket: Error %d\n",
WSAGetLastError());
WSACleanup();
return -1;
}
printf("Client connecting to: %s\n", hp->h_name);
if (connect(conn_socket, (struct sockaddr*)&server, sizeof(server))
== SOCKET_ERROR) {
fprintf(stderr, "connect() failed: %d\n", WSAGetLastError());
WSACleanup();
return -1;
}
loopcount = 0;
while (1) {
sprintf_s(Buffer, sizeof(Buffer), "This is a small test message [number %d]", loopcount++);
retval = send(conn_socket, Buffer, sizeof(Buffer), 0);
if (retval == SOCKET_ERROR) {
fprintf(stderr, "send() failed: error %d\n", WSAGetLastError());
WSACleanup();
return -1;
}
printf("Sent Data [%s]\n", Buffer);
retval = recv(conn_socket, Buffer, sizeof(Buffer), 0);
if (retval == SOCKET_ERROR) {
fprintf(stderr, "recv() failed: error %d\n", WSAGetLastError());
closesocket(conn_socket);
WSACleanup();
return -1;
}
if (retval == 0) {
printf("Server closed connection\n");
closesocket(conn_socket);
WSACleanup();
return -1;
}
printf("Received %d bytes, data [%s] from server\n", retval, Buffer);
if (!loopflag){
printf("Terminating connection\n");
break;
}
else {
if ((loopcount >= maxloop) && (maxloop >0))
break;
else
Sleep(2000);
}
}
closesocket(conn_socket);
WSACleanup();
}
In server.cpp where you're reading/writing the UDP socket:
else if (FD_ISSET(udp_socket, &SockSet))
{
retval = recvfrom(msgsock, Buffer, sizeof(Buffer), 0,
(struct sockaddr *)&from, &fromlen);
printf("Received datagram from %s\n", inet_ntoa(from.sin_addr));
...
printf("Echoing same data back to client\n");
retval = sendto(msgsock, Buffer, sizeof(Buffer), 0,
(struct sockaddr *)&from, fromlen);
if (retval == SOCKET_ERROR) {
fprintf(stderr, "send() failed: error %d\n", WSAGetLastError());
}
printf("UDP server looping back for more requests\n");
}
You're using msgsock in your recv and send calls (as well as closesocket), which you use for the accepted TCP socket, instead of udp_socket.
Change msgsock to udp_socket in this block and it should work.
i created a server and client application in tcp using c++. the client just sends a message to the server.
in the code the server displays some information about the client in the console: ip address, port etc
i want the server to store the client's ip address because a different application is then going to access this list
so how can i store the ip address of all the clients that connect to the server?
server code:
WSADATA wsaData;
SOCKET ListeningSocket, NewConnection;
SOCKADDR_IN ServerAddr, SenderInfo; quantity
int Port = 7171;
char recvbuff[1024];
int ByteReceived, i, nlen;
ListeningSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (ListeningSocket == INVALID_SOCKET)
{
printf("Server: Error at socket, error code: %ld.\n", WSAGetLastError());
WSACleanup();
return 1;
}
ServerAddr.sin_family = AF_INET;
ServerAddr.sin_port = htons(Port);
ServerAddr.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(ListeningSocket, (SOCKADDR *)&ServerAddr, sizeof(ServerAddr)) == SOCKET_ERROR)
{
printf("Server: bind failed! Error code: %ld.\n", WSAGetLastError());
closesocket(ListeningSocket);
WSACleanup();
return 1;
}
if (listen(ListeningSocket, 5) == SOCKET_ERROR)
{
printf("Server: listen: Error listening on socket %ld.\n", WSAGetLastError());
closesocket(ListeningSocket);
WSACleanup();
return 1;
}
else
{
printf("Server: listening for connections...\n\n");
}
while(1)
{
NewConnection = SOCKET_ERROR;
while(NewConnection == SOCKET_ERROR)
{
NewConnection = accept(ListeningSocket, NULL, NULL);
printf("Server: New client got connected, ready to receive and send data...\n\n");
ByteReceived = recv(NewConnection, recvbuff, sizeof(recvbuff), 0);
if ( ByteReceived > 0 )
{
getsockname(ListeningSocket, (SOCKADDR *)&ServerAddr, (int *)sizeof(ServerAddr));
printf("Server: IP(s) used by Server: %s\n", inet_ntoa(ServerAddr.sin_addr));
printf("Server: port used by Server: %d\n\n", htons(ServerAddr.sin_port));
memset(&SenderInfo, 0, sizeof(SenderInfo));
nlen = sizeof(SenderInfo);
getpeername(NewConnection, (SOCKADDR *)&SenderInfo, &nlen);
printf("Server: IP used by Client: %s\n", inet_ntoa(SenderInfo.sin_addr));
printf("Server: Port used by Client: %d\n", htons(SenderInfo.sin_port));
printf("Server: Bytes received: %d\n", ByteReceived);
printf("Server: Message from client: \"");
for(i=0;i < ByteReceived;i++)
{
printf("%c", recvbuff[i]);
}
printf("\"");
}
else if ( ByteReceived == 0 )
{
printf("Server: Connection closed!\n");
}
else
{
printf("Server: recv failed with error code: %d\n", WSAGetLastError());
}
}
}
you can just collect inet_ntoa(SenderInfo.sin_addr) to a vector:
WSADATA wsaData;
SOCKET ListeningSocket, NewConnection;
SOCKADDR_IN ServerAddr, SenderInfo; quantity
int Port = 7171;
char recvbuff[1024];
int ByteReceived, i, nlen;
ListeningSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (ListeningSocket == INVALID_SOCKET)
{
printf("Server: Error at socket, error code: %ld.\n", WSAGetLastError());
WSACleanup();
return 1;
}
ServerAddr.sin_family = AF_INET;
ServerAddr.sin_port = htons(Port);
ServerAddr.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(ListeningSocket, (SOCKADDR *)&ServerAddr, sizeof(ServerAddr)) == SOCKET_ERROR)
{
printf("Server: bind failed! Error code: %ld.\n", WSAGetLastError());
closesocket(ListeningSocket);
WSACleanup();
return 1;
}
if (listen(ListeningSocket, 5) == SOCKET_ERROR)
{
printf("Server: listen: Error listening on socket %ld.\n", WSAGetLastError());
closesocket(ListeningSocket);
WSACleanup();
return 1;
}
else
{
printf("Server: listening for connections...\n\n");
}
std::vector<std::string> vClientIPs; // client ip string vector
while(1)
{
NewConnection = SOCKET_ERROR;
while(NewConnection == SOCKET_ERROR)
{
NewConnection = accept(ListeningSocket, NULL, NULL);
printf("Server: New client got connected, ready to receive and send data...\n\n");
ByteReceived = recv(NewConnection, recvbuff, sizeof(recvbuff), 0);
if ( ByteReceived > 0 )
{
getsockname(ListeningSocket, (SOCKADDR *)&ServerAddr, (int *)sizeof(ServerAddr));
printf("Server: IP(s) used by Server: %s\n", inet_ntoa(ServerAddr.sin_addr));
vClientIPs.push_back(std::string(inet_ntoa(ServerAddr.sin_addr))); //insert client ip
printf("Server: port used by Server: %d\n\n", htons(ServerAddr.sin_port));
memset(&SenderInfo, 0, sizeof(SenderInfo));
nlen = sizeof(SenderInfo);
getpeername(NewConnection, (SOCKADDR *)&SenderInfo, &nlen);
printf("Server: IP used by Client: %s\n", inet_ntoa(SenderInfo.sin_addr));
printf("Server: Port used by Client: %d\n", htons(SenderInfo.sin_port));
printf("Server: Bytes received: %d\n", ByteReceived);
printf("Server: Message from client: \"");
for(i=0;i < ByteReceived;i++)
{
printf("%c", recvbuff[i]);
}
printf("\"");
}
else if ( ByteReceived == 0 )
{
printf("Server: Connection closed!\n");
}
else
{
printf("Server: recv failed with error code: %d\n", WSAGetLastError());
}
}
}
WRITE_IP_SOMEWHERE(vClientIPs); // you can write this string vector to a file or database