Re: How to send a uint8_t through a socket
Hi,
Here is the code.The value of b in the struc is going through but not
a .when i print it in the server side..nothing is getting printed.
I changed the code a little[from the first post so htons/ntonl is
used]
struct exam
{
uint8_t b;
uint32_t a;
};
////////////////////////////////////server
int main()
{
int listenSocket, connectSocket, i;
unsigned short int listenPort;
socklen_t clientAddressLength;
struct sockaddr_in clientAddress, serverAddress;
char line[LINE_ARRAY_SIZE];
cout << "Enter port number to listen on (between 1500 and 65000): ";
cin >> listenPort;
// Create socket for listening for client connection requests.
listenSocket = socket(AF_INET, SOCK_STREAM, 0);
if (listenSocket < 0) {
cerr << "cannot create listen socket";
exit(1);
}
serverAddress.sin_family = AF_INET;
serverAddress.sin_addr.s_addr = htonl(INADDR_ANY);
serverAddress.sin_port = htons(listenPort);
if (bind(listenSocket,
(struct sockaddr *) &serverAddress,
sizeof(serverAddress)) < 0) {
cerr << "cannot bind socket";
exit(1);
}
`
// Wait for connections from clients.
listen(listenSocket, 5);
while (1) {
cout << "Waiting for TCP connection on port " << listenPort <<
" ...\n";
clientAddressLength = sizeof(clientAddress);
connectSocket = accept(listenSocket,
(struct sockaddr *) &clientAddress,
&clientAddressLength);
if (connectSocket < 0) {
cerr << "cannot accept connection ";
exit(1);
}
// Show the IP address of the client.
cout << " connected to " << inet_ntoa(clientAddress.sin_addr);
char x[123];
exam *o;
while (recv(connectSocket,x,sizeof(exam), 0) > 0) {
cout <<((exam *)x)->a<<"\n";
cout <<((exam *)x)->b<<"\n";
}
}
////////////////////client
int main()
{
int socketDescriptor;
unsigned short int serverPort;
struct sockaddr_in serverAddress;
struct hostent *hostInfo;
char buf[MAX_LINE + 1], c;
uint8_t flag=3;
buf[0]=flag;
cout << "Enter server host name or IP address: ";
cin.get(buf, MAX_LINE, '\n');
hostInfo = gethostbyname(buf);
if (hostInfo == NULL) {
cout << "problem interpreting host: " << buf << "\n";
exit(1);
}
cout << "Enter server port number: ";
cin >> serverPort;
cin.get(c); // dispose of the newline
socketDescriptor = socket(AF_INET, SOCK_STREAM, 0);
if (socketDescriptor < 0) {
cerr << "cannot create socket\n";
exit(1);
}
serverAddress.sin_family = hostInfo->h_addrtype;
memcpy((char *) &serverAddress.sin_addr.s_addr,
hostInfo->h_addr_list[0], hostInfo->h_length);
serverAddress.sin_port = htons(serverPort);
if (connect(socketDescriptor,
(struct sockaddr *) &serverAddress,
sizeof(serverAddress)) < 0) {
cerr << "cannot connect\n";
exit(1);
}
exam *t1,t2;
t1=&t2;;
t2.a=21;
t2.b=1;
unsigned char x[10];
char *y=(char *)&t2;
// Stop when the user inputs a line with just a dot.
// Send the line to the server.
if (send(socketDescriptor,y,sizeof(exam), 0) < 0) {
cerr << "cannot send data ";
close(socketDescriptor);
exit(1);
}
}
return 0;
}