【发布时间】:2011-11-24 01:49:50
【问题描述】:
最近我一直在研究 C++ 中的套接字,我遇到了这个问题:
*(struct in_addr*)&serv_addr.sin_addr.s_addr = *(struct in_addr *)server->h_addr;
虽然这确实做到了我想要的,但我有点困惑为什么我不能这样做:
(struct in_addr)serv_addr.sin_addr.s_addr = *(struct in_addr *)server->h_addr;
既然它变成一个指针,然后立即被取消引用,第二个不应该和第一个一样好用吗?我还是 C++ 的新手,这让我有点困惑。任何帮助将不胜感激。下面是代码。它所做的只是获取主机名或 IP 并将 IP 打印到屏幕上。
#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's tell me if the address was copied correctly to serv_addr I believe.
return 0;
}
【问题讨论】:
-
如果您也可以发布类型声明会有所帮助。
标签: c++ sockets pointers struct dereference