I am having some difficulty with finding out how to correct the segmentation fault.
client.cpp
#include <errno.h>
#include <signal.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <netdb.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <arpa/inet.h>
using namespace std;
int call_socket(char *hostname, unsigned short portnum)
{
struct sockaddr_in sa;
struct hostent *hp;
int a;
int s;
if ((hp = gethostbyname(hostname)) == NULL)
{
errno = ECONNREFUSED;
return(-1);
}
memset(&sa, 0, sizeof(sa));
memcpy((char*) &sa.sin_addr, hp->h_addr, hp->h_length);
sa.sin_family = hp->h_addrtype;
sa.sin_port = htons((u_short)portnum);
if ((s=socket(hp->h_addrtype, SOCK_STREAM, 0)) < 0)
{
return(-1);
}
if (connect(s, (struct sockaddr*)&sa, sizeof (sa)) < 0)
{
close(s);
return(-1);
}
return(s);
}
int main(int argc, char* argv[])
{
int n;
int s;
int b;
char username[256];
string hostname;
string usern;
string terminated = "Server Terminated";
string doesnotexist = "does not exist.";
hostname = "localhost";
char *hostn[hostname.size()+1];
strcpy(*hostn, hostname.c_str());
cout << "Enter a server port number: " << endl;
cin >> s;
while (s <2000 || s > 65535)
{
cout << "Server port number must be between 2000 and 65535. Please enter the server port number again." << endl;
cin >> s;
}
if ((b = call_socket(*hostn,s)) < 0)
{
perror("call Socket");
exit(1);
}
cout << "Enter a user name: " << endl;
cin >> usern;
strcpy(username, usern.c_str());
n = write(b, username, strlen(username));
if (n < 0)
{
cout << "Error writing to socket" << endl;
}
bzero(username, 256);
n = read(b,username,255);
if (n < 0)
{
cout << "Error reading from socket" << endl;
}
if (username == terminated)
{
printf("%s\n",username);
}
else if (username == doesnotexist)
{
cout << "The username: " << usern << ", ";
printf("%s\n",username);
}
else
{
cout << "The public key for " << usern << " is: ";
printf("%s\n",username);
}
close(b);
return 0;
}
I tried valgrind and got: Conditional jump or move depends on uninitialised value(s), Use of uninitialised value of size 8, Invalid write of size 8. As I am unexperienced with valgrind, I don't really know how to fix it.
Your problem is almost certainly here:
char *hostn[hostname.size()+1];
strcpy(*hostn, hostname.c_str());
This has several issues:
hostn is a variable-length-array, which is not a standard part of C++
hostn is an array of char*, not an array of char
The pointers in hostn are uninitialized, and thus don't point anywhere useful.
You pass the first element of hostn to strcpy as the destination
Since strcpy will attempt to dereference the pointer passed to it and that pointer is uninitialized, that means your program's behavior is undefined.
Note that all of this could be avoided easily. Just get rid of hostn entirely. It's not serving any purpose beyond what hostname.c_str() already serves. Simply change call_socket to accept a const char* instead of a char*, and you can call it directly using hostname.c_str() (i.e. call_socket(hostname.c_str(), s))
Related
I use mincore to judge memory by mmap open in memory or disk. but return a set vector. Why? In fact the result must be a all clear vector, but I get all set.
This is my code. Why is line 28 (cout << "find" << endl;) always skipped?
/proc/pid/smap can see RSS is 0, but mincore return total file in memory.
#include <iostream>
#include <unistd.h>
#include <sys/mman.h>
#include <bitset>
#include <stdio.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <string.h>
using namespace std;
int main()
{
char* pData1 = NULL;
int fd1 = open("test_large_file_1", O_RDWR);
if (fd1 == -1)
{
cout << "file error ..." << endl;
return -1;
}
off_t size1 = lseek(fd1, 0, SEEK_END);
if (size1 == -1)
{
cout << "lseek error ..." << endl;
return -1;
}
pData1 = (char *)mmap(NULL, size1, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd1, 0 );
if (pData1 == MAP_FAILED)
{
cout << "mmap error ..." << endl;
return -1;
}
unsigned char *pVec = new unsigned char[size1 / 1024 / 4];
if (-1 == mincore(pData1, size1, pVec))
{
cout << "mincore error ..." << endl;
return -1;
}
for (int i = 0; i < size1 / 1024/ 4; ++i)
{
if (i % 1000 == 0)
cout << (int)pVec[i] << endl;
if ((pVec[i] & 1) == 0)
{
cout << "find" << endl;
break;
}
}
close(fd1);
munmap((void *)pData1, size1);
return 0;
}
I want to get whether an address by mmap opening in memory or not, veteran has some way?/
I need help.
I get a old file(don't open long time),mincore return a normal vector(has 0 and 1), but a new file(just now open or read ...),mincore return a all set bit vector.
This phenomenon is due to page cache, that will save recently page to cache, if a program repeatly open a file, the page of file will be get in memory .
I passed a structure pointer to a function. What I need is to get the string "connection refused"(return from ssh_get_error()) in the main function.
#include <libssh/libssh.h>
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <cstring>
using namespace std;
typedef struct rtns {
bool state;
char* desc;
} rtns;
int connect_host(rtns *con_host) {
const char* desc;
char desc2[1000];
ssh_session my_ssh_session;
int rc;
my_ssh_session = ssh_new();
if (my_ssh_session == NULL)
exit(-1);
ssh_options_set(my_ssh_session, SSH_OPTIONS_HOST, "localhost");
rc = ssh_connect(my_ssh_session);
if (rc != SSH_OK) {
(*con_host).state = false;
desc = ssh_get_error(my_ssh_session);
strcpy(desc2, ssh_get_error(my_ssh_session));
(*con_host).desc = strdup(desc2);
cout << "from connect_host function->" <<con_host->desc << "\n";
} else {
(*con_host).state = true;
}
ssh_disconnect(my_ssh_session);
ssh_free(my_ssh_session);
}
int main() {
rtns con_host;
rtns *p = (rtns*) malloc(sizeof(struct rtns));
p = (rtns*) malloc(20);
connect_host(&con_host);
cout << "from main function->" << *(con_host.desc) << "\n\n";
}
Output-
from connect_host function->Connection refused
from main function->C
The problem is that i am only getting one character "C" in the main function. I have some idea that I am doing memory allocation wrong but i have no idea how to do it correctly. I also tried to shift the malloc allocation in con_host function but it didn't work either.
Think about what you are printing. You pass to the stream a char, not a char *:
cout << "from main function->" << *(con_host.desc) << "\n\n";
// *(con_host.desc) = *(char *) = char
// Above is a simplification but you get the point.
So long as con_host.desc is a null terminated c string you can print it like this:
cout << "from main function->" << con_host.desc << "\n\n";
Here is a live example.
It's not memory allocation error. It's caused by the output statement. Change to
cout << "from main function->" << con_host.desc << "\n\n";
I need to send a string back to client that includes the cost of vehicle and the vehicle with modifier(carStyling). I want to return a string containing the sline and the cost to the client. Something like;
Your Sedan Offroad will cost $150000.
Paragraph below contains the code necessary.
#include <arpa/inet.h>
#include <netdb.h>
#include <netinet/in.h>
#include <unistd.h>
#include <iostream>
#include <cstring>
#include <stdlib.h>
#include <stdio.h>
#include <string>
#include <sstream>
#define MAX_MSG 100
#define LINE_ARRAY_SIZE (MAX_MSG+1)
using namespace std;
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);
}
// Bind listen socket to listen port. First set various
// fields in the serverAddress structure, then call
// bind().
// htonl() and htons() convert long integers and short
// integers (respectively) from host byte order (on x86
// this is Least Significant Byte first) to network byte
// order (Most Significant Byte first).
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. This is a
// non-blocking call; i.e., it registers this program with
// the system as expecting connections on this socket, and
// then this thread of execution continues on.
listen(listenSocket, 5);
while (1) {
cout << "Waiting for TCP connection on port " << listenPort << " ...\n";
// Accept a connection with a client that is requesting
// one. The accept() call is a blocking call; i.e., this
// thread of execution stops until a connection comes
// in. connectSocket is a new socket that the system
// provides, separate from listenSocket. We *could*
// accept more connections on listenSocket, before
// connectSocket is closed, but this program doesn't do
// that.
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.
// inet_ntoa() converts an IP address from binary form to the
// standard "numbers and dots" notation.
cout << " connected to " << inet_ntoa(clientAddress.sin_addr);
// Show the client's port number.
// ntohs() converts a short int from network byte order (which is
// Most Significant Byte first) to host byte order (which on x86,
// for example, is Least Significant Byte first).
cout << ":" << ntohs(clientAddress.sin_port) << "\n";
// Read lines from socket, using recv(), storing them in the line
// array. If no messages are currently available, recv() blocks
// until one arrives.
// First set line to all zeroes, so we'll know where the end of
// the string is.
memset(line, 0x0, LINE_ARRAY_SIZE);
while (recv(connectSocket, line, MAX_MSG, 0) > 0) {
cout << " -- " << line << "\n";
// Convert line to upper case.
for (i = 0; line[i] != '\0'; i++)
line[i] = toupper(line[i]);
// creating an object to direct line to a string array
std::string delimiter[2];
int i = 0;
double cost = 0;
std::string carType;
std::string carStyling;
std::string sline;
sline = line;
stringstream ssin(sline);
while (ssin.good() && i < 2){
ssin >> delimiter[i];
++i;
}
for(i = 0; i < 2; i++){
cout << delimiter[i] << endl;
}
if(i==0) {
carType = delimiter[0];
if(carType.compare("SEDAN")==0){
sline = "Your Sedan";
cost = 100000;
std::copy(sline.begin(), sline.end(), line);
line[sline.size()] = '\0';
}
else if(carType.compare("MPV")==0){
sline = "MPV";
cost = 120000;
std::copy(sline.begin(), sline.end(), line);
line[sline.size()] = '\0';
}
else if(carType.compare("SUV")==0){
sline = "SUV";
cost = 140000;
std::copy(sline.begin(), sline.end(), line);
line[sline.size()] = '\0';
}
else if(carType.compare("LUXURY")==0){
sline = "LUXURY";
cost = 180000;
std::copy(sline.begin(), sline.end(), line);
line[sline.size()] = '\0';
}
if(i==2) {
carStyling = delimiter[1];
if(carStyling.compare("SPORTY")==0){
sline += "Sporty";
cost = cost * 1.5;
}
else if(carStyling.compare("OFFROAD")==0){
sline += "Offroad";
cost = cost * 1.3;
}
}
}
// Send converted line back to client.
if (send(connectSocket, line, strlen(line) + 1, 0) < 0)
cerr << "Error: cannot send modified data";
memset(line, 0x0, LINE_ARRAY_SIZE); // set line to all zeroes
}
}
}
The other one here is the code for the client.cc
#include <netdb.h>
#include <netinet/in.h>
#include <unistd.h>
#include <iostream>
#include <cstring>
#include <stdlib.h>
#define MAX_LINE 100
#define LINE_ARRAY_SIZE (MAX_LINE+1)
using namespace std;
int main()
{
int socketDescriptor;
unsigned short int serverPort;
struct sockaddr_in serverAddress;
struct hostent *hostInfo;
char buf[LINE_ARRAY_SIZE], c;
cout << "Enter server host name or IP address: ";
cin.get(buf, MAX_LINE, '\n');
// gethostbyname() takes a host name or ip address in "numbers and
// dots" notation, and returns a pointer to a hostent structure,
// which we'll need later. It's not important for us what this
// structure is actually composed of.
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
// Create a socket. "AF_INET" means it will use the IPv4 protocol.
// "SOCK_STREAM" means it will be a reliable connection (i.e., TCP;
// for UDP use SOCK_DGRAM), and I'm not sure what the 0 for the last
// parameter means, but it seems to work.
socketDescriptor = socket(AF_INET, SOCK_STREAM, 0);
if (socketDescriptor < 0) {
cerr << "cannot create socket\n";
exit(1);
}
// Connect to server. First we have to set some fields in the
// serverAddress structure. The system will assign me an arbitrary
// local port that is not in use.
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);
}
cout << "\nWelcome to Car Customization Server. What are your orders?\n";
cout << ">> Type of vehicle: Sedan, MPV, SUV, Luxury\n";
cout << ">> Type of Styling: Sporty, Offroad\n";
cout << ">> Eg. To order type: MPV Sporty\n";
// Prompt the user for input, then read in the input, up to MAX_LINE
// charactars, and then dispose of the rest of the line, including
// the newline character.
cout << "Enter Order: ";
cin.get(buf, MAX_LINE, '\n');
while (cin.get(c) && c != '\n')
; //Loop does nothing except consume the spare bytes
// Stop when the user inputs a line with just a dot.
while (strcmp(buf, ".")) { //strcmp returns 0 when the two strings
//are the same, so this continues when
//they are different
// Send the line to the server.
if (send(socketDescriptor, buf, strlen(buf) + 1, 0) < 0) {
cerr << "cannot send data ";
close(socketDescriptor); //Note this is just like using files...
exit(1);
}
// Zero out the buffer.
memset(buf, 0x0, LINE_ARRAY_SIZE);
// Read the modified line back from the server.
if (recv(socketDescriptor, buf, MAX_LINE, 0) < 0) {
cerr << "didn't get response from server?";
close(socketDescriptor);
exit(1);
}
cout << "results: " << buf << "\n";
// Prompt the user for input, then read in the input, up to MAX_LINE
// charactars, and then dispose of the rest of the line, including
// the newline character. As above.
cout << "Enter Order: ";
cin.get(buf, MAX_LINE, '\n');
while (cin.get(c) && c != '\n')
; //again, consuming spare bytes
}
close(socketDescriptor);
return 0;
}
So there, if anyone knows how to send back both the string and the cost. Please reply. Thank you.
You can pack your std::string sline into sending buffer by copying bytes:
memcpy(line, sline.c_str(), strlen(sline.c_str()))
send it, and then on the client side unpack it the same way.
edit:
Try code below for you server, is this what you wanted?
#include <arpa/inet.h>
#include <netdb.h>
#include <netinet/in.h>
#include <unistd.h>
#include <iostream>
#include <cstring>
#include <stdlib.h>
#include <stdio.h>
#include <string>
#include <sstream>
#define MAX_MSG 100
#define LINE_ARRAY_SIZE (MAX_MSG+1)
using namespace std;
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;
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);
}
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);
}
cout << " connected to " << inet_ntoa(clientAddress.sin_addr);
cout << ":" << ntohs(clientAddress.sin_port) << "\n";
memset(line, 0x0, LINE_ARRAY_SIZE);
while (recv(connectSocket,line, MAX_MSG, 0) > 0) {
cout << " -- " << line << "\n";
std::string delimiter[2];
int i = 0;
double cost = 0;
std::string carType;
std::string carStyling;
std::string sline;
sline = line;
stringstream ssin(sline);
while (ssin.good() && i < 2){
ssin >> delimiter[i];
++i;
}
sline = "";
for(i = 0; i < 2; i++){
cout << delimiter[i] << endl;
}
sline += "Your ";
carType = delimiter[0];
if(carType.compare("Sedan")==0){
sline += "Sedan";
cost = 100000;
}
else if(carType.compare("MPV")==0){
sline += "MPV";
cost = 120000;
}
else if(carType.compare("SUV")==0){
sline += "SUV";
cost = 140000;
}
else if(carType.compare("Luxury")==0){
sline += "Luxury";
cost = 180000;
}
carStyling = delimiter[1];
if(carStyling.compare("Sporty")==0){
sline += " Sporty ";
cost = cost * 1.5;
}
else if(carStyling.compare("Offroad")==0){
sline += " Offroad ";
cost = cost * 1.3;
}
sline += "will cost ";
std::ostringstream ss;
ss << cost;
sline += ss.str();
sline.copy(line, sline.length());
if (send(connectSocket, line, strlen(line) + 1, 0) < 0)
cerr << "Error: cannot send modified data";
memset(line, 0x0, LINE_ARRAY_SIZE); // set line to all zeroes
}
}
}
I'm writing a client in C++ for my AI project that communicates with a server written in Java, to which I do not have access to the code. They use TCP sockets to communicate: the server sends me a message and the client performs an action accordingly, such as generating a move or updating the board or declaring victory, defeat and so on. Now I have noticed that sometimes the socket gets stuck and the server sends back a timeout message, even though the client has never generated a move and never entered in the "YOUR_MOVE" else if, which is weird, because it computes the move in no time (a handful of milliseconds) and if I add a 50 milliseconds sleep either before send or receive it works like a charm. I wonder what could possibly go wrong. That's the code:
#include <iostream>
#include <cstring> // Needed for memset
#include <sys/socket.h> // Needed for the socket functions
#include <netdb.h> // Needed for the socket functions
#include <unistd.h>
#include <string>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/lexical_cast.hpp>
#include <chrono>
#include "AI.cpp"
#include <locale>
#include <thread>
using namespace::std;
void error(const char *msg)
{
perror(msg);
exit(0);
}
class Client{
private:
AI* ai;
public:
int socketfd;
Client(const char* serverAddress, const char* port){
int status;
struct sockaddr_in serv_addr;
struct hostent *server;
portno = 8901;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR opening socket");
server = gethostbyname("127.0.0.1");
if (server == NULL) {
fprintf(stderr,"ERROR, no such host\n");
exit(0);
}
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy((char *)server->h_addr,
(char *)&serv_addr.sin_addr.s_addr,
server->h_length);
serv_addr.sin_port = htons(portno);
if (connect(sockfd,(struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0)
error("ERROR connecting");
ai = new AI();
(*ai).distance();
}
~Client(){
freeaddrinfo(host_info_list);
close(socketfd);
delete ai;
}
bool startsWith(char c1[], char c2[]){
int i=0;
while(c2[i] != 0){
if(c1[i]==0)
return false;
if(c1[i] != c2[i])
return false;
i++;
}
return true;
}
void substr(char c[], int pos, char* s){
int i;
for(i=pos; c[i]!=0; i++){
s[i-pos] = c[i];
}
s[i-pos] = 0;
}
void play(){
bzero(buffer,256);
n = read(sockfd,buffer,255);
if(startsWith(buffer, (char*)"WELCOME"))
printf(buffer);
string colour;
if(buffer[9]=='l')
colour="black";
else
colour="white";
char* msg = new char[256];
while(true){
bzero(buffer,256);
n = read(sockfd,buffer,255);
//printf(buffer);
if(startsWith(buffer, (char*)"VALID_MOVE"))
cout << "Valid move, please wait" << endl;
else if(startsWith(buffer, (char*)"OPPONENT_MOVE")){
substr(buffer, 14, msg);
ai->updateBoard(msg);
cout << "Opponent move: " << msg << endl;
}
else if(startsWith(buffer, (char*)"VICTORY")){
cout << "You win" << endl;
break;
}
else if(startsWith(buffer, (char*)"DEFEAT")){
cout << "You lose" <<endl;
break;
}
else if(startsWith(buffer, (char*)"TIE")){
cout << "You tied" << endl;
break;
}
else if(startsWith(buffer, (char*)"YOUR_TURN")){
cout << "YOUR_TURN branch" << endl;
string move = ai->generateNextMove(colour, 3);
cout << "Your move is: " << move << endl;
int i;
for(i=0;i<8; i++){
msg[i] = move.at(i);
}
msg[i] = 0;
sprintf(buffer, "MOVE %s\n", msg);
std::this_thread::sleep_for(std::chrono::milliseconds(40));
n = write(sockfd,buffer,strlen(buffer));
ai->updateBoard(move);
}
else if(startsWith(buffer, (char*)"TIMEOUT")){
cout << "Time out" << endl;
break;
}
else if(startsWith(buffer, (char*)"MESSAGE")){
substr(buffer, 8, msg);
cout << msg << endl;
}
}
close(sockfd);
}
};
int main()
{
const char serverAddr[]="127.0.0.1";
const char port[]="8901";
Client * client = new Client(serverAddr, port);
client->play();
delete client;
return 0;
}
P.S. This is my first post, please show forgiveness if I have involuntarily forgotten to provide some other information. Thank you.
For what I can see you are taking for granted that when you perform socket read with
n = read(sockfd,buffer,255);
You seem to be sure that you always receive an entire command, but think what happens if you receive only "YOUR TU" instead of "YOUR TURN"
You always clean the buffer and the next loop you receive just "RN" so you never process the command and the server remains waiting for your move.
What you should do is clean the buffer ONLY when you have received a full meaningful command.
If you uncomment the:
//printf(buffer);
You can check if my theory is correct.
I use to code in Python. Now I'm trying C++. When I run the program I see the target address (w/ Wireshark) reverse, even if I use htonl. In Python this same program worked fine.
Follow the code. At the bottom I printed the result.
I'm using Ubuntu 12.04LTS and g++ (Ubuntu/Linaro 4.6.3).
//UdpClient.cpp
#include <iostream>
#include <string>
#include <sstream>
#include <sys/socket.h>
#include <sys/types.h>
#include <netdb.h>
#include <cstdlib>
#include <arpa/inet.h>
#include <typeinfo>
using namespace std;
int main(int argc, char* argv[])
{
int s, p, rb,rs;
int bytesend;
char buf[1024];
int len;
char ent[16];
char Porta[5];
unsigned long EndServ;
struct sockaddr_in UdpServer, UdpClient;
int UdpServerLen = sizeof(UdpServer);
//do text
string msg("The quick brown fox jumps over the lazy dog\n");
len = msg.copy(buf, msg.size(), 0);
buf[len] = '\0';
//do socket
s = socket(AF_INET, SOCK_DGRAM, 0);
if (s == -1){
cout << "No socket done\n";
}
else {
cout << "Socket done\n";
}
//populate UdpClient struct
UdpClient.sin_family = AF_INET;
UdpClient.sin_addr.s_addr = INADDR_ANY;
UdpClient.sin_port = 0;
//populate UdpServer struct
UdpServer.sin_family = AF_INET;
UdpServer.sin_addr.s_addr = inet_addr(argv[1]);
//check if addres is correct
cout << "ServerAddress: " << hex << UdpServer.sin_addr.s_addr << endl;
UdpServer.sin_port = htons(atoi(argv[2]));
//bind socket
rb = bind(s, (struct sockaddr *)&UdpClient, sizeof(UdpClient));
if (rb == 0){
cout << "Bind OK!\n";
}
else {
cout << "Bind NOK!!!\n";
close(s);
exit(1);
}
//send text to Server
cout << "UdpServSiz: " << sizeof(UdpServer) << endl;
rs = sendto(s, buf, 1024, 0, (struct sockaddr *)&UdpServer, sizeof(UdpServer));
if (rs == -1){
cout << "Message NOT sent!!!\n";
}
else {
cout << "Message SENT!!!\n";
}
close(s);
return 0;
}
/*
edison#edison-AO532h:~/CmmPGMs$ ./UdpClient 127.0.0.1 6789
Socket done
ServerAddress: 100007f (using htonl or not!!)
Bind OK!
Message SENT!!!
edison#edison-AO532h:~/CmmPGMs$
*/
Sounds like you're on ARM (Linaro)? In which case the endianness of the processor matches network order, so htonl and ntohl basically do nothing.