Convert IP Address from std::string to boost::uint32 - c++11

Is there any function in the Boost library, in which I can convert and IPv4 address given as string:
std::string ip_address = "192.168.0.1";
Into a binary format as following "11000000101010000000000000000001" and store it in a boost::unit32 unit, or I should build the function by myself?
Also what about converting an IPv6 address from std::string into 4 * unit32, is there any function to convert it into octets?

Boost.Asio will get you there, as in:
boost::asio::ip::address_v4::from_string("192.168.0.1").to_ulong();
IPv6 is a little more complicated, as you have to use boost::asio::ip::address_v6::from_string(addr).to_bytes() which returns a boost::array<unsigned char, 16> and convert from that yourself.

Related

A more comprehensive function than recordScalar that stores structured data as value instead of storing a double number

One of the most widely used functions for output generation in Omnet++ is recordScalar.
virtual void recordScalar (cComponent *component, const char *name, double value, opp_string_map *attributes=nullptr)=0
Is there a more comprehensive function than recordScalar that stores structured data as value instead of storing a double number? Or coding it ourselves.
Or coding a similar function to write mentioned outputs in a text file in the format of JSON by that function?
By structured data, I mean struct data type in c++. like this:
struct logtype {
int src;
int dest;
int messagescount; // the count of messages transmitted between src and dest and vice versa
};
Thanks
OMNeT++ does not contain ready to use tool for storing complex structures. However, OMNeT++ uses C++ and one can write own method that will store some data to a text file, or to a JSON file, or to any file.

passing pointers

I have this declared above:
char PandaImage[] = "images/panda.png";
SDL_Texture* PandaTexture = nullptr;
I have a function to create textures:
void LoadMedia( SDL_Texture *ThisTexture, char *Image )
{
SDL_Surface* TempSurface = nullptr;
.......................
ThisTexture = SDL_CreateTextureFromSurface( gRenderer, TempSurface );
I call it as:
LoadMedia( PandaTexture, PandaImage );
It builds, logs the image loaded and texture created, but no image
If I hard change the line ( use Panda directly instead of This ):
PandaTexture = SDL_CreateTextureFromSurface( gRenderer, TempSurface );
My image is there.
I have always had trouble with & * and passing.
Is there a good, simple help for me?
Thanks for your kind help - back to Google for now
In short, I think you could solve your problem by changing the function to:
void LoadMedia( SDL_Texture** thisTexture, char* Image)
{
...
(*thisTexture) = SDL_CreateTextureFromSurface( gRenderer, TempSurface);
}
And by calling the function using:
LoadMedia( &PandaTexture, PandaImage);
An explanation:
Variables and Pointers
A variable is used to store data (a primitive or a class instance). For example:
int a = 10;
stores an integer in memory. This means, that symbol 'a' now represents number 10, which is stored somewhere in your computer's memory as 4 bytes.
A pointer is used to store an address (this address points towards a variable). For example:
int* a_address = 1234;
says that there is an integer stored at address 1234 in your computer's memory. A pointer always takes up the same amount of space (4 bytes on a 32 bit machine and 8 bytes on a 64 bit machine), as it simply stores an address.
Getting the Address of a Variable [&]
You will rarely ever set the address of a pointer yourself. Often, pointers are the result of a "new" call. Using "new" reserves memory to store an instance of the class you want to create, and returns the address of the object. In essence, it says: "I created an object for you, and you can find it at this location in your memory".
Alternatively, when you have a normal variable (primitive of class instance), you can find its address by using the & character. For example:
int a = 10;
int* a_address = &a;
says: "store the location of variable a in pointer a_address. Why would you do this? Say you have a very large instance (for example an SDL_Texture consisting of many, many pixels) and you want to pass it to a function (or pass it back outside of the function). If you were to pass it to the function as SDL_Texture thisTexture, you are copying the entire object (a so-called pass by value). This is time consuming. Alternatively, you could simply pass the address to the function, as an SDL_Texture * thisTexture. This is a so called pass by reference, and it is much faster as you can imagine.
Getting the Variable at an Address [*]
Obviously, if you have an address, you also need a way to get the actual variable at that address. This is done using the * character. It is called "dereferencing". For example:
int a = 10;
int* a_address = &a;
int b = (*a_address);
This last line says: "Give me the variable, stored at address a_address, and put it in b".
Function Parameters Going Out-of-scope
When a function ends, its local variables (including parameters) go out-of-scope. This means that their memory is freed (for variables, not for dynamically allocated objects stored as pointers!). Their values will be forgotten. In your case, you are passing an SDL_Texture * as a parameter. This means, a copy is made of the address stored in PandaTexture. This address is copied over to thisTexture. You then write the return value of SDL_CreateTextureFromSurface to thisTexture. Next the function ends, and thisTexture goes out-of-scope. As a result, the location of your SDL_Texture (the SDL_Texture * pointer) is lost forever. You actually want to store the address to pointer PandaTexture, but as you can see, the address is only written to thisTexture.
Solution: How to Fix your Function
We can fix this by passing a pointer, to your pointer called PandaTexture. A "pointer to a pointer" is written as:
SDL_Surface** thisTexture;
We want to pass the address of pointer PandaTexture to this. This way, we can write to PandaTexture from inside your method! After all, we know where PandaTexture stores its pointer in memory, allowing us to change it. To actually put the address of PandaTexture in it, we need to use the & character in the function call as such:
LoadMedia(&PandaTexture, PandaImage);
Next, inside of our function, we want to change the value of PandaTexture. However, we were passed &PandaTexture and not PandaTexture itself. To write the value of &PandaTexture (the address where our texture will be stored), we need dereferencing, as such:
(*thisTexture) = SDL_CreateTextureFromSurface(gRenderer, TempSurface);
This works because: "thisTexture is a pointer to a pointer to an SDL_Texture (aka an SDL_Texture**). By dereferencing it, we obtain a pointer to an SDL_Texture (aka an SDL_Texture*). Here we can store the return value of the SDL_CreateTextureFromSurface function.
Why do we not run into out-of-scope issues here? Parameter thisTexture will still go out of scope, and its value will be forgotten. But! We didn't write to thisTexture, instead we wrote our SDL_Texture * pointer to the address that thisTexture points to! This bit of memory is not cleared due to scoping, so we can view the results from outside the function!
In summary, you can solve your problem using a pointer to a pointer. I hope the above clears up the concepts of pointers, variables, addresses and dereferencing a bit!

How to assign/bind a known function to a variable?

I wonder how to make a variable within IDA Pro bound to some function so the next time I double click the variable it will send me to the function.
v1 = this
*v2 = Known-Function
At Some Different location:
char __stdcall ClassA__KnownFunction(ClassA *ClassA, void a2) {
commands.....
}
I know you can set type to int, struct, dword etc. But I am looking for some method to point the variable to already known offset/function in IDA Pro.
Function pointer is merely a variable that holds the address of a function; you cannot treat a variable like a constant. You have two options:
Add the name of the function as a comment (just for the sake of documentation).
Get rid of the variable assignment, hard-code the function address by editing the hex, and then perform the analysis again.

UnicodeString storage type

My application needs to manage a few of unicode strings (<10). The content of these strings is dynamic and can change through application run. To store strings I am using objects of type UnicodeString.
One approach to solving this problem is to create as many member variables as there are unicode strings like for example:
UnicodeString str1;
UnicodeString str2;
...
UnicodeString strN;
This solutions is pretty simple at least at first glance. But there is problem with scalability. If the number of string would rise in the future, we risk creating hard-to-read bigg code. So I thougth creating something like this for managing strings:
std::map<HWND, UnicodeString> file_names; ///< member variable of form TForm1
Every string is connected with some edit box. I can use window handle as key to dictionary.
What I don't understand - who should be responsible for allocating and deallocating space for storing unicode string in this case? Lets say I create UnicodeString variable on local stack:
void TForm1::ProcessFile(TEdit *edit_box)
{
UnicodeString str = "C:\\Temp\\ws.gdb";
file_name[edit_box->Handle] = str;
}
Will the content of str variable survive end of member function ProcessFile?
The memory storage of a UnicodeString is reference counted and managed by the RTL for you. You do not need to worry about deallocating it yourself, unless you allocate the UnicodeString itself using the new operator. In your code snippet, the str variable will be freed when ProcessFile() exits, but its contents will survive because file_name still has an active reference to it.
Do not use an HWND as the key for your std::map. The window managed by the TWinControl::Handle property is dynamic and can change value during the lifetime of the app. You can, however, use the TEdit* pointer instead:
std::map<TEdit*, UnicodeString> file_names;
void TForm1::ProcessFile(TEdit *edit_box)
{
UnicodeString str = "C:\\Temp\\ws.gdb";
file_names[edit_box] = str;
}

Convert NSData to NSString

I am receiving a successful connection to the server and i am in my callback function:
I am trying to get the name of the host and print that to my console:
if(theType == kCFSocketConnectCallBack){
NSLog(#"Connection is accepted");
CFSocketNativeHandle nativeSocket = CFSocketGetNative(theSocket);
uint8_t name[SOCK_MAXADDRLEN];
socklen_t namelen = sizeof(name);
NSData *peer = nil;
if (getpeername(nativeSocket, (struct sockaddr *)name, &namelen) == 0) {
peer = [NSData dataWithBytes:name length:namelen];
NSString *string = [[NSString alloc] initWithData:peer encoding:NSUTF8StringEncoding];
NSLog(#"IP adress of connected peer: %#", string);
}
When i run the application in the debug mode i can see the IP address value assigned to name , so it's successful in getting the name , each value is uint8_t..
The peer length is showing me 16;
My problem converting it to NSData then NSString...
output:
2010-01-31 13:57:58.671 IP adress of connected peer: (null)
My string is being output as NULL,
Any advise is appreciated, thanks....
getpeername() doesn't return the host name of the remote side; it returns the address:
$ man getpeername
...
DESCRIPTION
The getpeername() function returns the address of the peer connected to
the specified socket.
You want getnameinfo():
$ man getnameinfo
...
DESCRIPTION
The getnameinfo() function is used to convert a sockaddr structure to a
pair of host name and service strings. It is a replacement for and pro-
vides more flexibility than the gethostbyaddr(3) and getservbyport(3)
functions and is the converse of the getaddrinfo(3) function.
or gethostbyaddr():
$ man gethostbyaddr
...
DESCRIPTION
The getaddrinfo(3) and getnameinfo(3) functions are preferred over the
gethostbyname(), gethostbyname2(), and gethostbyaddr() functions.
The gethostbyname(), gethostbyname2() and gethostbyaddr() functions each
return a pointer to an object with the following structure describing an
internet host referenced by name or by address, respectively.
sockaddr is a struct, not just a typedef for a character array. You need to pass getpeername the address to an actual sockaddr struct, and then build the string from the sa_data field of that struct--and that's assuming that sa_data is actually a string for your address type, which the documentation doesn't suggest you can actually count on. As another answer says, this is not the call you want if your goal is to get a string representation to print out.
(Also, you don't need an NSData at all to go from a character array to an NSString; you can just use -[NSString initWithBytes:length:encoding:])
First, check to make sure that peer contains an instance of NSData that is non-zero in length.
If it does, then the most likely problem is that the data is not properly of the specified encoding causing NSString to fail the encoding and return a nil string. If it is an encoding issue, there is API on NSString for doing lossy encodings. Even if lossy isn't acceptable in your final solution, going that route can be quite helpful to figuring out what is going wrong.
That assumes by NULL you really mean nil. It would be helpful to paste the exact output of the log line.

Resources