5.3. bind() —我在哪个端口上?

本文详细解释了bind()函数在Socket编程中的应用,包括其原型、参数及如何将其与特定端口关联。通过示例展示了如何使用bind()函数绑定套接字到指定端口,并讨论了AI_PASSIVE标志的作用。

原文:https://beej.us/guide/bgnet/html/#bind

 

5.3. bind() — 我在哪个端口上?

       一旦你有一个套接字,你可能要将套接字和机器上的一定的端口关联起来。(如果你想用listen()来侦听一定端口的数据,这是必要一步---比如,开始玩多人网络游戏告诉你要连接到192.168.5.10的3490端口)

使用的端口号是由内核相匹配传入的数据包到某个进程的socket描述符。

如果你只想用connect()(因为你是客户端,不是服务器端),那么这个步骤没有必要。但是无论如何,请继续读下去。

 

       下面是他的原型:

#include<sys/types.h>

#include<sys/socket.h>



int bind(int sockfd, struct sockaddr *my_addr, int addrlen);
  • sockfd     是调用 socket() 返回的文件描述符。
  • my_addr 是指向数据结构 struct sockaddr 的指针,它保存你的地址(即端口和 IP 地址) 信息。
  • addlen    是这个地址(struct socketaddr)的长度。

   

简单得很不是吗? 再看看例子:

struct addrinfo hints, *res;
int sockfd;

// first, load up address structs with getaddrinfo():

memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;  // use IPv4 or IPv6, whichever
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;     // fill in my IP for me

getaddrinfo(NULL, "3490", &hints, &res);

// make a socket:

sockfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);

// bind it to the port we passed in to getaddrinfo():

bind(sockfd, res->ai_addr, res->ai_addrlen);

 

通过使用AI_PASSIVE标志,我告诉程序将其绑定到正在运行的主机的IP。

如果要绑定到特定的本地IP地址,请删除AI_PASSIVE并将IP地址放入getaddrinfo()的第一个参数中。

      

bind()如果返回-1表示出错。

 

讲解旧代码部分省略…

 

 

2025-08-26 17:34:36.210 ERROR 27004 --- [ main] o.s.boot.SpringApplication : Application run failed org.springframework.context.ApplicationContextException: Failed to start bean &#39;shadedNettyGrpcServerLifecycle&#39;; nested exception is java.lang.IllegalStateException: Failed to start the grpc server at org.springframework.context.support.DefaultLifecycleProcessor.doStart(DefaultLifecycleProcessor.java:182) ~[spring-context-5.3.31.jar:5.3.31] at org.springframework.context.support.DefaultLifecycleProcessor.access$200(DefaultLifecycleProcessor.java:54) ~[spring-context-5.3.31.jar:5.3.31] at org.springframework.context.support.DefaultLifecycleProcessor$LifecycleGroup.start(DefaultLifecycleProcessor.java:357) ~[spring-context-5.3.31.jar:5.3.31] at java.lang.Iterable.forEach(Iterable.java:75) ~[na:1.8.0_362-362] at org.springframework.context.support.DefaultLifecycleProcessor.startBeans(DefaultLifecycleProcessor.java:156) ~[spring-context-5.3.31.jar:5.3.31] at org.springframework.context.support.DefaultLifecycleProcessor.onRefresh(DefaultLifecycleProcessor.java:124) ~[spring-context-5.3.31.jar:5.3.31] at org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:946) ~[spring-context-5.3.31.jar:5.3.31] at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:594) ~[spring-context-5.3.31.jar:5.3.31] at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:147) ~[spring-boot-2.7.18.jar:2.7.18] at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:732) [spring-boot-2.7.18.jar:2.7.18] at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:409) [spring-boot-2.7.18.jar:2.7.18] at org.springframework.boot.SpringApplication.run(SpringApplication.java:308) [spring-boot-2.7.18.jar:2.7.18] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1300) [spring-boot-2.7.18.jar:2.7.18] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1289) [spring-boot-2.7.18.jar:2.7.18] at com.tplink.nbu.demo.basicspringboot.BasicSpringBootApplication.main(BasicSpringBootApplication.java:13) [classes/:na] Caused by: java.lang.IllegalStateException: Failed to start the grpc server at net.devh.boot.grpc.server.serverfactory.GrpcServerLifecycle.start(GrpcServerLifecycle.java:74) ~[grpc-server-spring-boot-autoconfigure-2.14.0.RELEASE.jar:2.14.0.RELEASE] at org.springframework.context.support.DefaultLifecycleProcessor.doStart(DefaultLifecycleProcessor.java:179) ~[spring-context-5.3.31.jar:5.3.31] ... 14 common frames omitted Caused by: java.io.IOException: Failed to bind to address /127.0.0.0:8091 at io.grpc.netty.shaded.io.grpc.netty.NettyServer.start(NettyServer.java:328) ~[grpc-netty-shaded-1.56.1.jar:1.56.1] at io.grpc.internal.ServerImpl.start(ServerImpl.java:184) ~[grpc-core-1.51.0.jar:1.51.0] at io.grpc.internal.ServerImpl.start(ServerImpl.java:93) ~[grpc-core-1.51.0.jar:1.51.0] at net.devh.boot.grpc.server.serverfactory.GrpcServerLifecycle.createAndStartGrpcServer(GrpcServerLifecycle.java:113) ~[grpc-server-spring-boot-autoconfigure-2.14.0.RELEASE.jar:2.14.0.RELEASE] at net.devh.boot.grpc.server.serverfactory.GrpcServerLifecycle.start(GrpcServerLifecycle.java:72) ~[grpc-server-spring-boot-autoconfigure-2.14.0.RELEASE.jar:2.14.0.RELEASE] ... 15 common frames omitted Caused by: java.net.BindException: Cannot assign requested address: bind at sun.nio.ch.Net.bind0(Native Method) ~[na:1.8.0_362-362] at sun.nio.ch.Net.bind(Net.java:461) ~[na:1.8.0_362-362] at sun.nio.ch.Net.bind(Net.java:453) ~[na:1.8.0_362-362] at sun.nio.ch.ServerSocketChannelImpl.bind(ServerSocketChannelImpl.java:222) ~[na:1.8.0_362-362] at io.grpc.netty.shaded.io.netty.channel.socket.nio.NioServerSocketChannel.doBind(NioServerSocketChannel.java:141) ~[grpc-netty-shaded-1.56.1.jar:1.56.1] at io.grpc.netty.shaded.io.netty.channel.AbstractChannel$AbstractUnsafe.bind(AbstractChannel.java:562) ~[grpc-netty-shaded-1.56.1.jar:1.56.1] at io.grpc.netty.shaded.io.netty.channel.DefaultChannelPipeline$HeadContext.bind(DefaultChannelPipeline.java:1334) ~[grpc-netty-shaded-1.56.1.jar:1.56.1] at io.grpc.netty.shaded.io.netty.channel.AbstractChannelHandlerContext.invokeBind(AbstractChannelHandlerContext.java:600) ~[grpc-netty-shaded-1.56.1.jar:1.56.1] at io.grpc.netty.shaded.io.netty.channel.AbstractChannelHandlerContext.bind(AbstractChannelHandlerContext.java:579) ~[grpc-netty-shaded-1.56.1.jar:1.56.1] at io.grpc.netty.shaded.io.netty.channel.DefaultChannelPipeline.bind(DefaultChannelPipeline.java:973) ~[grpc-netty-shaded-1.56.1.jar:1.56.1] at io.grpc.netty.shaded.io.netty.channel.AbstractChannel.bind(AbstractChannel.java:260) ~[grpc-netty-shaded-1.56.1.jar:1.56.1] at io.grpc.netty.shaded.io.netty.bootstrap.AbstractBootstrap$2.run(AbstractBootstrap.java:356) ~[grpc-netty-shaded-1.56.1.jar:1.56.1] at io.grpc.netty.shaded.io.netty.util.concurrent.AbstractEventExecutor.runTask(AbstractEventExecutor.java:174) ~[grpc-netty-shaded-1.56.1.jar:1.56.1] at io.grpc.netty.shaded.io.netty.util.concurrent.AbstractEventExecutor.safeExecute(AbstractEventExecutor.java:167) ~[grpc-netty-shaded-1.56.1.jar:1.56.1] at io.grpc.netty.shaded.io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks(SingleThreadEventExecutor.java:470) ~[grpc-netty-shaded-1.56.1.jar:1.56.1] at io.grpc.netty.shaded.io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:569) ~[grpc-netty-shaded-1.56.1.jar:1.56.1] at io.grpc.netty.shaded.io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:997) ~[grpc-netty-shaded-1.56.1.jar:1.56.1] at io.grpc.netty.shaded.io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74) ~[grpc-netty-shaded-1.56.1.jar:1.56.1] at io.grpc.netty.shaded.io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30) ~[grpc-netty-shaded-1.56.1.jar:1.56.1] at java.lang.Thread.run(Thread.java:750) ~[na:1.8.0_362-362]
最新发布
08-27
Caused by: org.springframework.data.redis.RedisConnectionFailureException: Unable to connect to Redis; nested exception is io.lettuce.core.RedisConnectionException: Unable to connect to localhost:6379 at org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory$ExceptionTranslatingConnectionProvider.translateException(LettuceConnectionFactory.java:1689) ~[spring-data-redis-2.7.18.jar:2.7.18] at org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory$ExceptionTranslatingConnectionProvider.getConnection(LettuceConnectionFactory.java:1597) ~[spring-data-redis-2.7.18.jar:2.7.18] at org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory$SharedConnection.getNativeConnection(LettuceConnectionFactory.java:1383) ~[spring-data-redis-2.7.18.jar:2.7.18] at org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory$SharedConnection.getConnection(LettuceConnectionFactory.java:1366) ~[spring-data-redis-2.7.18.jar:2.7.18] at org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory.getSharedConnection(LettuceConnectionFactory.java:1093) ~[spring-data-redis-2.7.18.jar:2.7.18] at org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory.getConnection(LettuceConnectionFactory.java:421) ~[spring-data-redis-2.7.18.jar:2.7.18] at org.springframework.data.redis.core.RedisConnectionUtils.fetchConnection(RedisConnectionUtils.java:193) ~[spring-data-redis-2.7.18.jar:2.7.18] at org.springframework.data.redis.core.RedisConnectionUtils.doGetConnection(RedisConnectionUtils.java:144) ~[spring-data-redis-2.7.18.jar:2.7.18] at org.springframework.data.redis.core.RedisConnectionUtils.getConnection(RedisConnectionUtils.java:105) ~[spring-data-redis-2.7.18.jar:2.7.18] at org.springframework.data.redis.core.RedisTemplate.execute(RedisTemplate.java:211) ~[spring-data-redis-2.7.18.jar:2.7.18] at org.springframework.data.redis.core.RedisTemplate.execute(RedisTemplate.java:191) ~[spring-data-redis-2.7.18.jar:2.7.18] at org.springframework.data.redis.core.RedisTemplate.hasKey(RedisTemplate.java:782) ~[spring-data-redis-2.7.18.jar:2.7.18] at com.yssq.mes.common.gateway.configuration.DynamicRouteAutoConfiguration.healthIndicator(DynamicRouteAutoConfiguration.java:75) ~[classes/:na] at com.yssq.mes.common.gateway.configuration.DynamicRouteAutoConfiguration$$EnhancerBySpringCGLIB$$cf2b6d02.CGLIB$healthIndicator$0(<generated>) ~[classes/:na] at com.yssq.mes.common.gateway.configuration.DynamicRouteAutoConfiguration$$EnhancerBySpringCGLIB$$cf2b6d02$$FastClassBySpringCGLIB$$464c31e8.invoke(<generated>) ~[classes/:na] at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:244) ~[spring-core-5.3.39.jar:5.3.39] at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:331) ~[spring-context-5.3.39.jar:5.3.39] at com.yssq.mes.common.gateway.configuration.DynamicRouteAutoConfiguration$$EnhancerBySpringCGLIB$$cf2b6d02.healthIndicator(<generated>) ~[classes/:na] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_321] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_321] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_321] at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_321] at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154) ~[spring-beans-5.3.39.jar:5.3.39] ... 20 common frames omitted Caused by: io.lettuce.core.RedisConnectionException: Unable to connect to localhost:6379 at io.lettuce.core.RedisConnectionException.create(RedisConnectionException.java:78) ~[lettuce-core-6.1.10.RELEASE.jar:6.1.10.RELEASE] at io.lettuce.core.RedisConnectionException.create(RedisConnectionException.java:56) ~[lettuce-core-6.1.10.RELEASE.jar:6.1.10.RELEASE] at io.lettuce.core.AbstractRedisClient.getConnection(AbstractRedisClient.java:330) ~[lettuce-core-6.1.10.RELEASE.jar:6.1.10.RELEASE] at io.lettuce.core.RedisClient.connect(RedisClient.java:216) ~[lettuce-core-6.1.10.RELEASE.jar:6.1.10.RELEASE] at org.springframework.data.redis.connection.lettuce.StandaloneConnectionProvider.lambda$getConnection$1(StandaloneConnectionProvider.java:115) ~[spring-data-redis-2.7.18.jar:2.7.18] at java.util.Optional.orElseGet(Optional.java:267) ~[na:1.8.0_321] at org.springframework.data.redis.connection.lettuce.StandaloneConnectionProvider.getConnection(StandaloneConnectionProvider.java:115) ~[spring-data-redis-2.7.18.jar:2.7.18] at org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory$ExceptionTranslatingConnectionProvider.getConnection(LettuceConnectionFactory.java:1595) ~[spring-data-redis-2.7.18.jar:2.7.18] ... 41 common frames omitted Caused by: io.netty.channel.AbstractChannel$AnnotatedConnectException: Connection refused: no further information: localhost/127.0.0.1:6379 Caused by: java.net.ConnectException: Connection refused: no further information at sun.nio.ch.SocketChannelImpl.checkConnect(Native Method) ~[na:1.8.0_321] at sun.nio.ch.SocketChannelImpl.finishConnect(SocketChannelImpl.java:715) ~[na:1.8.0_321] at io.netty.channel.socket.nio.NioSocketChannel.doFinishConnect(NioSocketChannel.java:337) ~[netty-transport-4.1.101.Final.jar:4.1.101.Final] at io.netty.channel.nio.AbstractNioChannel$AbstractNioUnsafe.finishConnect(AbstractNioChannel.java:334) ~[netty-transport-4.1.101.Final.jar:4.1.101.Final] at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:776) ~[netty-transport-4.1.101.Final.jar:4.1.101.Final] at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:724) ~[netty-transport-4.1.101.Final.jar:4.1.101.Final] at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:650) ~[netty-transport-4.1.101.Final.jar:4.1.101.Final] at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:562) ~[netty-transport-4.1.101.Final.jar:4.1.101.Final] at io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:997) ~[netty-common-4.1.101.Final.jar:4.1.101.Final] at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74) ~[netty-common-4.1.101.Final.jar:4.1.101.Final] at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30) ~[netty-common-4.1.101.Final.jar:4.1.101.Final] at java.lang.Thread.run(Thread.java:750) ~[na:1.8.0_321]
06-28
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值