gpt4 book ai didi

c - 绑定(bind)到 C 中的特定 IP for ubuntu

转载 作者:太空宇宙 更新时间:2023-11-04 06:40:26 25 4
gpt4 key购买 nike

您好,我正在尝试制作一个简单的服务器,它从 getaddrinfo() 获取 IP 地址并绑定(bind)到它。使用 ifconfig,我发现我有一个 wlan0 192.168.2.10 的 IP 地址,我想绑定(bind)到它。不幸的是,我绑定(bind)的地址似乎是我的 lo 设备。出于某种原因,当我初始化 getaddrinfo("192.168.2.10","3490",&hings,&res); res 返回一个 NULL 指针。我将在下面展示我的代码。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <signal.h>

#define MAXDATASIZE 500;

int main(int argc, char *argv[]){
// dealing with client socket
struct sockaddr_storage their_addr;
socklen_t addr_size;
// server socket
struct addrinfo serverSide,*serverInfo,*sortIP;
int optValRet;
int listenSock, newSock;
// this is for reading in information
char buf[501];
char point[INET6_ADDRSTRLEN];
char compare[INET6_ADDRSTRLEN] = "192.168.2.10";
// this is for handeling child processes and signals
struct sigaction sa;
sa.sa_handler = NULL;
sigemptyset(&sa.sa_mask);
sa.sa_flags = SA_RESTART;
if(sigaction(SIGCHLD, &sa, NULL) == -1){
printf("We have a problem, sigaction is not working.\n");
perror("\n");
exit(1);
}
// this sets up addrinfo
memset(&serverSide, 0, sizeof serverSide);
serverSide.ai_family = AF_UNSPEC;
serverSide.ai_socktype = SOCK_STREAM;
serverSide.ai_flags = INADDR_ANY;
// set up the address
if(getaddrinfo("192.168.2.10","3490",&serverSide,&serverInfo)!=0){
printf("get addr not success\n");
perror("\n");
return 1;
}

printf("Got address lists\n");

for(sortIP = serverInfo; sortIP = sortIP->ai_next; sortIP != NULL){

if((listenSock = socket(sortIP->ai_family, sortIP->ai_socktype, sortIP->ai_protocol))==-1){
continue;
}
if(setsockopt(listenSock,SOL_SOCKET,SO_REUSEADDR,&optValRet,sizeof(int))==-1){
perror("\n");
exit(1);
}
if(bind(listenSock,sortIP->ai_addr,sortIP->ai_addrlen) == -1 ){
perror("\n");
close(listenSock);
continue;
}
break;
}
if(sortIP == NULL){printf("sort ip is null.");}
inet_ntop(sortIP->ai_family,sortIP->ai_addr,point,sizeof point);
printf("Tell the clients connect to ip address %s on port 3490\n",point);
listen(listenSock, 10);
addr_size = sizeof their_addr;
newSock = accept(listenSock,(struct sockaddr *)&their_addr,&addr_size);
recv(newSock, buf, 500, 0);
printf("%s\n",buf);
close(listenSock);
close(newSock);
freeaddrinfo(serverInfo);
return 0;
}

现在,除了要返回 null 这一事实之外,我还有其他一些问题。由于 wifi 路由器为我的子网分配了 192.168.2.10 的 IP 地址,如果我在网络之外并试图联系我的服务器,我如何找出我的 IP 地址是什么?我假设内部网络 ip 与外部网络 ip 不同......我错了吗?无论如何,这是我的两个问题。

感谢您的帮助!

最佳答案

这是错误的,是您的直接问题:

for (sortIP = serverInfo; sortIP = sortIP->ai_next; sortIP != NULL)

你想要这样的东西:

for (sortIP = serverInfo; sortIP != NULL; sortIP = sortIP->ai_next)

但我个人会使用 while 循环。

关于c - 绑定(bind)到 C 中的特定 IP for ubuntu,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9146747/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com