I recently worked on sockets in C ++, and I came across this:
*(struct in_addr*)&serv_addr.sin_addr.s_addr = *(struct in_addr *)server->h_addr;
While this does what I want, I am a little confused why I cannot do this:
(struct in_addr)serv_addr.sin_addr.s_addr = *(struct in_addr *)server->h_addr;
Since it becomes a pointer, and then immediately dereferenced, you should not do the second job, as well as the first? I'm still new to C ++ and this is a bit confusing to me. Any help would be greatly appreciated. Below is the code. All it does is the host name or IP address and prints the IP address on the screen.
#include <iostream> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <arpa/inet.h> using namespace std; int main(){ int socketfd, portno, rwResult; struct sockaddr_in serv_addr; struct hostent* server; char inputName[50]; //The next block gets the host name and port number and stores them in variables cout<<"Enter host(Max Size 50): "; cin>>inputName; cout<<endl<<"Enter port number: "; cin>>portno; cout<<endl; server = gethostbyname(inputName); serv_addr.sin_family = AF_INET; serv_addr.sin_port = htons(portno); *(struct in_addr*)&serv_addr.sin_addr.s_addr = *(struct in_addr *)server->h_addr; //This is where I am confused //(struct in_addr)serv_addr.sin_addr.s_addr = *(struct in_addr *)server->h_addr; cout<< "Server: "<<inet_ntoa(*(struct in_addr *)server->h_addr_list[0])<<endl; cout<< "Server: "<<inet_ntoa(*(struct in_addr *)&serv_addr.sin_addr.s_addr)<<endl; //The two cout tell me if the address was copied correctly to serv_addr I believe. return 0; }
source share