cannot send nor receive data through sockets - c++

I tried making a simple server-client socket communication but something seems to no work properly with the server. I get this error whenever I send or receive:
Socket operation on non-socket: Socket operation on non-socket
Strangely enough, this only appears whenever the server is sending.
the client seems to be ok:
//server
#include <iostream>
#include <sys/socket.h>
#include <string.h>
#include <netinet/in.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <arpa/inet.h>
using namespace std;
int main(){
const int PORT = 5000;
int serverfd, clientfd, opt=1, n_send, n_recv;
sockaddr_in server_address, client_address;
char recvbuf[1024], sendbuf[1024];
bzero(&server_address , sizeof(server_address));
inet_pton(AF_INET, "127.0.0.1",&server_address.sin_addr);
int x = INADDR_ANY;
server_address.sin_family = AF_INET;
server_address.sin_port = htons(PORT);
socklen_t addrSize = sizeof(server_address);
if((serverfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0){
perror(strerror(errno));
exit(EXIT_FAILURE);
}
if((setsockopt(serverfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt))) < 0){
perror(strerror(errno));
exit(EXIT_FAILURE);
}
if((bind(serverfd, (sockaddr*)&server_address, sizeof(server_address)))< 0){
perror(strerror(errno));
exit(EXIT_FAILURE);
}
if((listen(serverfd, 1))< 0){
perror(strerror(errno));
exit(EXIT_FAILURE);
}
if((clientfd = accept(serverfd, (sockaddr *)&server_address, (socklen_t*)&addrSize) < 0)){
perror(strerror(errno));
exit(EXIT_FAILURE);
}
while (true){
cout << "SAY TO CLIENT: ";
bzero(sendbuf, sizeof(sendbuf));
cin >> sendbuf;
cout << endl;
send(clientfd, sendbuf, strlen(sendbuf), 0);
errno = 0;
bzero(recvbuf, sizeof(recvbuf));
if((n_recv = recv(clientfd, recvbuf, sizeof(recvbuf), MSG_WAITALL))< 0){
perror(strerror(errno));
exit(EXIT_FAILURE);
}
cout << recvbuf << endl;
}
return 0;
}
//client
#include <iostream>
#include <sys/socket.h>
#include <string.h>
#include <netinet/in.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <arpa/inet.h>
using namespace std;
int main(){
const int PORT = 5000;
int sockfd, n_send, n_recv;
char recvbuf[1024], sendbuf[1024];
sockaddr_in server_address;
bzero(&server_address, sizeof(server_address));
server_address.sin_family= AF_INET;
server_address.sin_port = htons(PORT);
inet_pton(AF_INET, "127.0.0.1", &server_address.sin_addr);
if((sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0){
perror(strerror(errno));
exit(EXIT_FAILURE);
}
if(connect(sockfd, (sockaddr *) &server_address, sizeof(server_address))<0){
perror(strerror(errno));
exit(EXIT_FAILURE);
}
while (true){
if((n_recv = recv(sockfd, recvbuf, sizeof(recvbuf), MSG_WAITALL)) < 0){
perror(strerror(errno));
exit(EXIT_FAILURE);
}
cout << "Server: " << recvbuf << endl;
cout << "Say to server: ";
cin >> sendbuf;
cout << endl;
if((n_send = send(sockfd, sendbuf, sizeof(sendbuf), 0)) < 0){
perror(strerror(errno));
exit(EXIT_FAILURE);
}
}
return 0;
}

clientfd is assigned a non-socket value. If we change the whitespace in your if:
if((clientfd =
accept(serverfd, (sockaddr *)&server_address, (socklen_t*)&addrSize) < 0
)) {
perror(strerror(errno));
exit(EXIT_FAILURE);
}
Because of the way you wrote it, the result of accept (the presumably valid socket) is checked, and that result is set to clientFd. Note that your parenthesis placement doesn't match your other lines.

Related

UDP client can not recieve data from server in C++

I am new for C++. I tried to write a UDP client and server in C++. The server can receive data from client. But the client can not receive data from server. No matter what data the server sends, the method recvfrom in client always returns 0.
The client code is below:
#include <winsock2.h>
#include <stdio.h>
#include <string.h>
#include <iostream>
using namespace std;
#pragma comment(lib, "ws2_32.lib")
#define BUFFER_SIZE 1024
int main()
{
SOCKET sock_Client;
WSADATA WSAData;
char receBuf[BUFFER_SIZE];
char sendBuf[BUFFER_SIZE];
if (WSAStartup(MAKEWORD(2, 2), &WSAData) != 0)
{
printf("initialation fails!");
return -1;
}
sock_Client = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
SOCKADDR_IN addr_server;
addr_server.sin_family = AF_INET;
addr_server.sin_port = htons(4567);
addr_server.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
SOCKADDR_IN sock;
int len = sizeof(sock);
while (true)
{
cout << "input data to send:";
cin >> sendBuf;
sendto(sock_Client, sendBuf, strlen(sendBuf), 0, (SOCKADDR*)&addr_server, sizeof(SOCKADDR));
//int last=recv(sock_Client, receBuf, strlen(receBuf), 0); //
int last = recvfrom(sock_Client, receBuf, strlen(receBuf), 0, (SOCKADDR*)&sock, &len);
if (last > 0)
{
receBuf[last] = '\0';
if (strcmp(receBuf, "bye") == 0)
{
cout << "server stops talking..." << endl;
closesocket(sock_Client);
break;
}
else
{
printf("received data:%s\n", receBuf);
}
}
}
closesocket(sock_Client);
WSACleanup();
return 0;
}
The server code:
#include <winsock2.h>
#include <stdio.h>
#include <string.h>
#include <iostream>
using namespace std;
#pragma comment(lib, "ws2_32.lib")
#define BUFFER_SIZE 1024
int main()
{
WSADATA WSAData;
char receBuf[BUFFER_SIZE];
char Response[BUFFER_SIZE];
if (WSAStartup(MAKEWORD(2, 2), &WSAData) != 0)
{
printf("initialation fails!");
exit(1);
}
SOCKET sockServer = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (sockServer == INVALID_SOCKET)
{
printf("Failed socket() \n");
return 0;
}
SOCKADDR_IN addr_Server;
addr_Server.sin_family = AF_INET;
addr_Server.sin_port = htons(4567);
addr_Server.sin_addr.S_un.S_addr = INADDR_ANY;
if (bind(sockServer, (SOCKADDR*)&addr_Server, sizeof(addr_Server)) == SOCKET_ERROR)
{
printf("Failed socket() %d \n", WSAGetLastError());
return 0;
}
SOCKADDR_IN addr_Clt;
int fromlen = sizeof(SOCKADDR);
while (true)
{
int last = recvfrom(sockServer, receBuf, 1024, 0, (SOCKADDR*)&addr_Clt, &fromlen);
if (last > 0)
{
receBuf[last] = '\0';
if (strcmp(receBuf, "bye") == 0)
{
cout << " client stop talking..." << endl;
closesocket(sockServer);
return 0;
}
else
{
printf("received data(%s):%s\n", inet_ntoa(addr_Clt.sin_addr), receBuf);
}
}
cout << "anser client:";//<br>Response = “”;
cin >> Response;
sendto(sockServer, Response, strlen(Response), 0, (SOCKADDR*)&addr_Clt, sizeof(SOCKADDR));
}
closesocket(sockServer);
WSACleanup();
return 0;
}
Anyone know what is wrong with the code?
The code runs in Windows. So, set(CMAKE_CXX_STANDARD 14) has to be added into CMakeLists.txt. If you want to run the code, please notice that.

OpenSSL in C++ Socket Connection (HTTPS Client)

i wrote an script, who can create an connection to an HTTP Server and shows the content of the website in the console.
Very easy.
But i want to connect to an https server and do the same procedures.
I searched at google and didn't found what i searched.
Please help me and give me an tutorial who can i use the openssl library.
I tried myself on the openssl library, but the library is very complicated and difficult to understand.
Here is my code of the http client:
#include <iostream>
#include <ctype.h>
#include <cstring>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <netinet/in.h>
#include <unistd.h>
#include <sstream>
#include <fstream>
#include <string>
#include <arpa/inet.h>
#include <openssl/ssl.h>
using namespace std;
int sock;
struct sockaddr_in client;
int PORT = 80;
int main(int argc, char const *argv[])
{
bzero(&client, sizeof(client));
client.sin_family = AF_INET;
client.sin_port = htons( PORT );
client.sin_addr.s_addr = inet_addr("172.16.0.6");
sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock < 0) {
cout << "Error creating socket." << endl;
exit(1);
}
if ( connect(sock, (struct sockaddr *)&client, sizeof(client)) < 0 ) {
close(sock);
cout << "Could not connect" << endl;
exit(1);
}
stringstream ss;
ss << "GET /" << "\r\n"
<< "Host: 172.16.1.4\r\n"
<< "Accept: application/json\r\n"
<< "Connection: close"
<< "\r\n\r\n";
string request = ss.str();
if (send(sock, request.c_str(), request.length(), 0) != (int)request.length()) {
cout << "Error sending request." << endl;
exit(1);
}
char cur;
while ( read(sock, &cur, 1) > 0 ) {
cout << cur;
}
return 0;
}
Here is a sample SSL client that connects to https://about.google/intl/en/ and prints downloaded a page : SSLClient.cpp
//============================================================================
// Name : SSLClient.cpp
// Compiling : g++ -c -o SSLClient.o SSLClient.cpp
// g++ -o SSLClient SSLClient.o -lssl -lcrypto
//============================================================================
#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <string.h>
using namespace std;
SSL *ssl;
int sock;
int RecvPacket()
{
int len=100;
char buf[1000000];
do {
len=SSL_read(ssl, buf, 100);
buf[len]=0;
printf("%s\n",buf);
// fprintf(fp, "%s",buf);
} while (len > 0);
if (len < 0) {
int err = SSL_get_error(ssl, len);
if (err == SSL_ERROR_WANT_READ)
return 0;
if (err == SSL_ERROR_WANT_WRITE)
return 0;
if (err == SSL_ERROR_ZERO_RETURN || err == SSL_ERROR_SYSCALL || err == SSL_ERROR_SSL)
return -1;
}
}
int SendPacket(const char *buf)
{
int len = SSL_write(ssl, buf, strlen(buf));
if (len < 0) {
int err = SSL_get_error(ssl, len);
switch (err) {
case SSL_ERROR_WANT_WRITE:
return 0;
case SSL_ERROR_WANT_READ:
return 0;
case SSL_ERROR_ZERO_RETURN:
case SSL_ERROR_SYSCALL:
case SSL_ERROR_SSL:
default:
return -1;
}
}
}
void log_ssl()
{
int err;
while (err = ERR_get_error()) {
char *str = ERR_error_string(err, 0);
if (!str)
return;
printf(str);
printf("\n");
fflush(stdout);
}
}
int main(int argc, char *argv[])
{
int s;
s = socket(AF_INET, SOCK_STREAM, 0);
if (s < 0) {
printf("Error creating socket.\n");
return -1;
}
struct sockaddr_in sa;
memset (&sa, 0, sizeof(sa));
sa.sin_family = AF_INET;
sa.sin_addr.s_addr = inet_addr("173.194.222.139"); // address of google.ru
sa.sin_port = htons (443);
socklen_t socklen = sizeof(sa);
if (connect(s, (struct sockaddr *)&sa, socklen)) {
printf("Error connecting to server.\n");
return -1;
}
SSL_library_init();
SSLeay_add_ssl_algorithms();
SSL_load_error_strings();
const SSL_METHOD *meth = TLSv1_2_client_method();
SSL_CTX *ctx = SSL_CTX_new (meth);
ssl = SSL_new (ctx);
if (!ssl) {
printf("Error creating SSL.\n");
log_ssl();
return -1;
}
sock = SSL_get_fd(ssl);
SSL_set_fd(ssl, s);
int err = SSL_connect(ssl);
if (err <= 0) {
printf("Error creating SSL connection. err=%x\n", err);
log_ssl();
fflush(stdout);
return -1;
}
printf ("SSL connection using %s\n", SSL_get_cipher (ssl));
char *request = "GET https://about.google/intl/en/ HTTP/1.1\r\n\r\n";
SendPacket(request);
RecvPacket();
return 0;
}
Note that if you want to exchange data between client and server with openssl, you might need to process error codes SSL_ERROR_WANT_READ and SSL_ERROR_WANT_WRITE as described in documentation. But it's not necessary here as HTTPS protocol is serial.

Making an HTTP Request with Sockets through a proxy

I would like to make an HTTP request using sockets. Here is my code so far:
#include "stdafx.h"
#ifndef UNICODE
#define UNICODE
#endif
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#define WIN32_LEAN_AND_MEAN
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdio.h>
#include <iostream>
#pragma comment(lib, "ws2_32.lib")
using namespace std;
int main()
{
try {
WSADATA wsaData;
int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
sockaddr_in clientService;
SOCKET Socket = socket(AF_INET, SOCK_STREAM, 0);
memset(&clientService, 0, sizeof(clientService));
clientService.sin_addr.s_addr = inet_addr("83.233.53.59"); // Proxy IP
clientService.sin_family = AF_INET;
clientService.sin_port = htons(10200);
if (bind(Socket, (struct sockaddr *) &clientService, sizeof(clientService)) < 0) {
perror("bind");
exit(1);
}
system("pause");
return 0;
struct hostent *host;
host = gethostbyname("www.google.com");
SOCKADDR_IN SockAddr;
SockAddr.sin_port = htons(80);
SockAddr.sin_family = AF_INET;
// SockAddr.sin_addr.s_addr = *((unsigned long*)host->h_addr);
memcpy(host->h_addr, &(SockAddr.sin_addr.s_addr), host->h_length);
std::cout << "Connecting...\n";
iResult = connect(Socket, (SOCKADDR *)& clientService, sizeof(clientService));
if (iResult != 0) {
std::cout << "Could not connect";
getchar();
return 1;
}
std::cout << "Connected.\n";
send(Socket, "GET / HTTP / 1.1\r\nHost: www.google.com\r\nConnection: close\r\n\r\n", strlen("GET / HTTP / 1.1\r\nHost: www.google.com\r\nConnection: close\r\n\r\n"), 0);
char buffer[10000];
int nDataLength;
while ((nDataLength = recv(Socket, buffer, 10000, 0)) > 0) {
int i = 0;
while (buffer[i] >= 32 || buffer[i] == '\n' || buffer[i] == '\r') {
std::cout << buffer[i];
i += 1;
}
}
iResult = closesocket(Socket);
WSACleanup();
system("pause");
}
catch (...) {
system("pause");
}
return 0;
}
But it doesn't work, without the program closes itself without leaving me the HTML source of the webpage. What's wrong?
How can I fix it?
This works on my machine, but I'm not on a windows machine. I'm on a freeBSD (OS X) machine. Having problems getting gethostbyname to resolve, not sure what that's about, but this worked and connected and downloaded the code from google.
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#define WIN32_LEAN_AND_MEAN
//#include <winsock2.h>
//#include <ws2tcpip.h>
#include <stdio.h>
#include <iostream>
#pragma comment(lib, "ws2_32.lib")
using namespace std;
int main()
{
try {
// WSADATA wsaData;
// int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
// sockaddr_in clientService;
int Socket = socket(AF_INET, SOCK_STREAM, 0);
/*
memset(&clientService, 0, sizeof(clientService));
clientService.sin_addr.s_addr = inet_addr("83.233.53.59"); // Proxy IP
clientService.sin_family = AF_INET;
clientService.sin_port = htons(10200);
if (bind(Socket, (struct sockaddr *) &clientService, sizeof clientService) == -1) {
perror("bind");
exit(1);
}
system("pause");
return 0;
*/
const char hostname[] ="www.google.com";
struct hostent * host;
// host = gethostbyname(hostname);
sockaddr_in SockAddr;
memset(&SockAddr, 0, sizeof(SockAddr));
SockAddr.sin_port = htons(80);
SockAddr.sin_family = AF_INET;
SockAddr.sin_addr.s_addr = inet_addr("83.233.53.59");
// memcpy(host->h_addr, &(SockAddr.sin_addr.s_addr), host->h_length);
std::cout << "Connecting...\n";
int iResult = connect(Socket, (struct sockaddr *)& SockAddr, sizeof(SockAddr));
if (iResult != 0) {
std::cout << "Could not connect";
getchar();
return 1;
}
std::cout << "Connected.\n";
send(Socket, "GET / HTTP / 1.1\r\nHost: www.google.com\r\nConnection: close\r\n\r\n", strlen("GET / HTTP / 1.1\r\nHost: www.google.com\r\nConnection: close\r\n\r\n"), 0);
char buffer[10000];
int nDataLength;
while ((nDataLength = recv(Socket, buffer, 10000, 0)) > 0) {
int i = 0;
while (buffer[i] >= 32 || buffer[i] == '\n' || buffer[i] == '\r') {
std::cout << buffer[i];
i += 1;
}
}
iResult = close(Socket);
// WSACleanup();
system("pause");
}
catch (...) {
system("pause");
}
return 0;
}
It had an authentication failure at the http: level, but Heres the output:
Connecting...
Connected.
HTTP/1.0 401 Unauthorized
Server: uhttpd/1.0.0
Date: Thu, 17 Dec 2015 18:29:04 GMT
WWW-Authenticate: Basic realm=" "
Content-Type: text/html; charset="UTF-8"
Connection: close
<HTML><HEAD><META http-equiv='Pragma' content='no-cache'><META http-equiv='Cache-Control' content='no-cache'><TITLE> 401 Authorization</TITLE>
<script language=javascript type=text/javascript>
function cancelevent()
{
sh: pause: command not found
Program ended with exit code: 0
One thing that might go wrong is that your application may crash when it accesses an out-of-bound array index during the following loop:
while (buffer[i] >= 32 || buffer[i] == '\n' || buffer[i] == '\r') {
...
i += 1;
}
Your current code cannot guarantee the buffer contains a byte that would make your loop terminate, therefore it might continue indefinitely. You must prevent this by having an extra check before accessing the array index. Considering that nDataLength will always be smaller or equal to sizeof(buffer), try this:
while (i < nDataLength &&
(buffer[i] >= 32 || buffer[i] == '\n' || buffer[i] == '\r'))
{
// Do your printing.
i++;
}
Or maybe simpler:
while (buffer[i] >= 32 || buffer[i] == '\n' || buffer[i] == '\r')
{
// Do your printing.
i++;
if (i >= nDataLength)
break; // Exit the loop.
}
system("pause");
return 0;
This code prevents anything following from executing. Remove.
There are numerous other problems with your code. For example, you're binding the socket to the proxy address. That doesn't make sense. Remove. You're about to connect the socket, you don't need to bind it at all.
Then you're sending an invalid GET request to the proxy. The GET request in this case should contain the full URL, not just a relative URL.
You're overrunning the receive buffer when you search for the space etc. You need to bound that search by the count returned by recv().
And so on.

socket connection recvfrom no response C++

I am trying to get data from UDP broadcast, but no response from recvfrom function. Connection, binding, everything looks fine.
Can there be a problem with the broadcast?
Is there anyway I can check the exact error?
#include <iostream>
using namespace std;
//#include <ServerSocket.h>
#include <cstring>
#include <sys/socket.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
enter code here
int status;
int socketfd;
int enableMulticast = 1; // Argument for set socket
struct addrinfo host_info; // The struct that getaddrinfo() fills up with data.
struct addrinfo *host_info_list; // Pointer to the to the linked list of host_info's.
struct sockaddr_in socketAddr;
unsigned char incomming_data_buffer[IN_LEN];
socklen_t socklen;
#ifndef IN_LEN
#define IN_LEN 4096
#endif
memset(&host_info, 0, sizeof host_info);
memset(&socketAddr, 0, sizeof(struct sockaddr_in));
cout << "Setting up the structs..." << endl;
host_info.ai_family = AF_UNSPEC; // IP version not specified. Can be both.
host_info.ai_socktype = SOCK_DGRAM; // Use SOCK_STREAM for TCP or SOCK_DGRAM for UDP.
host_info.ai_protocol = IPPROTO_UDP; // The protocol type for UDP. If left as zero, it will return all types
status = getaddrinfo("UDP IP Address","Port", &host_info, &host_info_list);
socketfd = socket(host_info_list->ai_family, host_info_list->ai_socktype,
host_info_list->ai_protocol);
if (socketfd == -1) cout << "socket error " ;
else cout << "socket created successfully " ;
status = setsockopt(socketfd, SOL_SOCKET, SO_REUSEADDR, &enableMulticast, sizeof(enableMulticast));
socketAddr.sin_family = AF_INET;
socketAddr.sin_port = htons(INT_PORT);
socketAddr.sin_addr.s_addr = htonl(INADDR_ANY);
status = bind(socketfd, (struct sockaddr *)&socketAddr, sizeof(struct sockaddr_in));
status = connect(socketfd, host_info_list->ai_addr, host_info_list->ai_addrlen);
if (status < 0) cout << "connect error" <<endl ;
cout << "Waiting to receive data..." << endl;
socklen = sizeof(struct socketAddr);
while(1){
status = recvfrom(socketfd, incomming_data_buffer, IN_LEN, 0, (struct sockaddr *)&socketAddr, &socklen);
if(status >= 0) {
cout << "data received" ;
freeaddrinfo(host_info_list);
close(socketfd);
exit(0);
}
}
}
if(status = 0)
This can never be true. (1) it's a typo for status == 0; (2) it should be status >= 0, i.e.status is the length of the datagram received.

How to make a full-duplex c++ winsock chat program

I'm trying to make a simple client-server chat program in C++. I wrote this, but my problem is that I can just send data from the server to the client. I want to have a full-duplex communication, and send data from client to server too.
Here is my code.
server :
#include "stdafx.h"
#include <WinSock2.h>
#include <winsock.h>
#include <stdio.h>
#include <iostream>
#include <string>
#define RCVBUFSIZE 32
using namespace std;
#pragma comment(lib, "Ws2_32.lib")
int main()
{
WSADATA wsadat;
SOCKET welcome_socket = INVALID_SOCKET;
string IpAddress;
int PortNom;
SOCKADDR_IN SockAddress;
//-----------------------------------------------
if (WSAStartup(MAKEWORD(2,2),&wsadat) !=NO_ERROR)
{
cout << "WSA intialization failed. \n";
WSACleanup();
return 1;
}
//------------------------------------------------
welcome_socket = socket(AF_INET , SOCK_STREAM , 0);
//--------------------------------------------------
cout << "Enter your ip address: ";
cin >> IpAddress;
cout << "Enter your port nomber:";
cin >> PortNom;
//---------------------------------------------------
SockAddress.sin_addr.s_addr = inet_addr (IpAddress.c_str());
SockAddress.sin_port = htons(PortNom);
SockAddress.sin_family = AF_INET;
//---------------------------------------------------
bind(welcome_socket,(SOCKADDR *)&SockAddress,sizeof(SockAddress));
listen(welcome_socket,1);
//----------------------------------------------------
SOCKET Comm_sock;
SOCKADDR_IN ClientAddr;
int AddressLen = sizeof (ClientAddr);
char *buffer = new char[13];
int turn= 0;
char* buf = new char[50];
char temp;
while (true)
{
Comm_sock = accept(welcome_socket,(SOCKADDR *)&ClientAddr , &AddressLen);
while (buf != "exit")
{
if (turn == 0)
{
cout << endl;
recv(Comm_sock,buf,50,0);
if(buf[0]=='e' && buf[1]=='x' && buf[2]=='i' && buf[3]=='t')
return 0;
cout << "MsG from client :"<< buf << endl;
cin.get(temp);
turn = 1;
}
if (turn == 1)
{
cout << "Enter MsG:";
cin.get(buf,50);
if (buf[0]=='e' && buf[1]=='x' && buf[2]=='i' && buf[3]=='t')
return 0;
send(Comm_sock,buf,strlen(buf)+1,0);
cin.get(temp);
turn=0;
}
}
}
and client:
#include "stdafx.h"
#include <winsock2.h>
#include <Ws2tcpip.h>
#include <stdio.h>
#include <iostream>
using namespace std;
// Link with ws2_32.lib
#pragma comment(lib, "Ws2_32.lib")
#define DEFAULT_BUFLEN 512
#define DEFAULT_PORT "12345"
//-------------------------------------
int main ()
{
WSADATA wsadata;
int iResult;
SOCKET ConnectSocket = INVALID_SOCKET;
struct sockaddr_in clientservice;
char *sendbuf ="";
char recvbuf[DEFAULT_BUFLEN];
char sendbuffer[512];
int recvbuflen = DEFAULT_BUFLEN;
int sendbuflen = 512;
//----------------------------------
iResult = WSAStartup(MAKEWORD(2,2),&wsadata);
//----------------------------------
ConnectSocket = socket(AF_INET,SOCK_STREAM , IPPROTO_TCP);
//-----------------------------------
clientservice.sin_family = AF_INET;
clientservice.sin_addr.s_addr = inet_addr( "127.0.0.1" );
clientservice.sin_port = htons( 11111 );
//-----------------------------------
iResult = connect (ConnectSocket,(SOCKADDR *)&clientservice ,sizeof(clientservice));
iResult = send( ConnectSocket, sendbuf, (int)strlen(sendbuf), 0 );
cout << "bytes Sent:" << iResult << "\n";
//-------------------------------------
iResult = shutdown(ConnectSocket ,SD_SEND);
if (iResult == SOCKET_ERROR)
{
printf("shutdown failed: %d\n", WSAGetLastError());
closesocket(ConnectSocket);
WSACleanup();
return 1;
}
do {
string reciev;
iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);
recvbuf[iResult]= 0 ;
cout << recvbuf << endl;
} while(true);
//------------------------------------------
closesocket(ConnectSocket);
WSACleanup();
}