Skip to content

Commit

Permalink
fix: conninfo returns server IP (#216)
Browse files Browse the repository at this point in the history
* fix: conninfo returns server IP

* format code
  • Loading branch information
nakasyou authored Nov 11, 2024
1 parent 350f9b7 commit c1b482c
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 23 deletions.
18 changes: 6 additions & 12 deletions src/conninfo.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import type { GetConnInfo } from 'hono/conninfo'
import type { AddressInfo } from 'net'
import type { HttpBindings } from './types'

/**
Expand All @@ -10,20 +9,15 @@ import type { HttpBindings } from './types'
export const getConnInfo: GetConnInfo = (c) => {
const bindings = (c.env.server ? c.env.server : c.env) as HttpBindings

const address = bindings.incoming.socket.address() as AddressInfo

if (!('address' in address)) {
return {
remote: {},
}
}
const address = bindings.incoming.socket.remoteAddress
const port = bindings.incoming.socket.remotePort
const family = bindings.incoming.socket.remoteFamily

return {
remote: {
address: address.address,
addressType:
address.family === 'IPv4' ? 'IPv4' : address.family === 'IPv6' ? 'IPv6' : 'unknown',
port: address.port,
address,
port,
addressType: family === 'IPv4' ? 'IPv4' : family === 'IPv6' ? 'IPv6' : void 0,
},
}
}
19 changes: 8 additions & 11 deletions test/conninfo.test.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,15 @@
import { Hono } from 'hono'
import type { AddressType, ConnInfo } from 'hono/conninfo'
import type { AddressInfo } from 'net'
import { getConnInfo } from '../src/conninfo'

describe('ConnInfo', () => {
it('Should works', async () => {
const app = new Hono().get('/', (c) => c.json(getConnInfo(c)))

const address: AddressInfo = {
address: '0.0.0.0',
family: 'IPv4',
port: 3030,
const socket = {
remoteAddress: '0.0.0.0',
remoteFamily: 'IPv4',
remotePort: 3030,
}
expect(
await (
Expand All @@ -19,18 +18,16 @@ describe('ConnInfo', () => {
{},
{
incoming: {
socket: {
address: () => address,
},
socket,
},
}
)
).json()
).toEqual({
remote: {
address: address.address,
addressType: address.family as AddressType,
port: address.port,
address: socket.remoteAddress,
addressType: socket.remoteFamily as AddressType,
port: socket.remotePort,
},
} satisfies ConnInfo)
})
Expand Down

0 comments on commit c1b482c

Please sign in to comment.