2013-08-29 37 views
8

這似乎是一個非常基本的問題,沒有一個優雅的解決方案/答案。如何訪問Meteor中的客戶端IP地址?

如何從(1)服務器或(2)客戶端訪問客戶端(遠程)IP地址?

+0

請參閱:http://stackoverflow.com/questions/102605/can-i-lookup-the-ip-address-of-a-hostname-from-javascript –

+0

不知道什麼cgi-bin是或如何使用它爲此目的...:/ – Chet

回答

7

如林所說,這是所有漂亮現在與流星有很多整合,而不是黑暗時代,我們不得不自己做。不過,我還將其封裝在可跟蹤所有打開的連接的軟件包中,並允許您查詢其IP地址:https://github.com/mizzao/meteor-user-status。它也做了一堆其他有用的東西。

1

您可以使用此包裝:https://github.com/gadicohen/meteor-headers。它在客戶端和服務器上獲取標題。

如果你想沒有包裝,你可以從上面的代碼中'激發'自己,要記住的是,在0.6.5之前,我們使用'隱藏'__meteor_bootstrap__.app和0.6.5後推薦改爲使用WebApp.connectHandler

+1

這是一個非常好的解決方案:) – Chet

+0

在服務器上不太適用 - 也許我做錯了:https://github.com/gadicohen/meteor-headers/問題/ 2 – Chet

2

在客戶端

headers = { 
    list: {}, 
    get: function(header, callback) { 
     return header ? this.list[header] : this.list; 
    } 
} 

Meteor.call('getReqHeaders', function(error, result) { 
    if (error) { 
     console.log(error); 
    } 
    else { 
     headers.list = result; 
    } 
}); 

在服務器:

headers = { 
    list: {}, 
    get: function(header) { 
     return header ? this.list[header] : this.list; 
    } 
}; 

var app = typeof WebApp != 'undefined' ? WebApp.connectHandlers : __meteor_bootstrap__.app; 
app.use(function(req, res, next) { 
    reqHeaders = req.headers; 
    return next(); 
}); 

Meteor.methods({ 
    'getReqHeader': function(header) { 
     return reqHeaders[header]; 
    }, 
    'getReqHeaders': function() { 
     return reqHeaders; 
    }, 
}); 
+1

現在已經過時。客戶IP現在通過核心'clientAddress'提供 - http://docs.meteor.com/#/full/meteor_onconnection –

14

獲取客戶端IP:

沒有一個http請求,在功能,你應該能夠得到clientIP與:

clientIP = this.connection.clientAddress; 
//EX: you declare a submitForm function with Meteor.methods and 
//you call it from the client with Meteor.call(). 
//In submitForm function you will have access to the client address as above 

隨着HTTP請求,並使用鐵路由器及其Router.map功能:

在有針對性的路線使用的動作功能:

clientIp = this.request.connection.remoteAddress; 
+0

Salut Florin,如何提及這個問題是[this one]的完美副本(http:///stackoverflow.com/questions/14843232/how-to-get-the-user-ip-address-in-meteor-server)? –

+1

我完全同意,當時我想發表評論,而不是回答,但我沒有足夠的聲望點(在不屬於你的問題/答案上發表評論需要50p或更多) –

+0

This僅在版本0.7.1.1之後適用於那些應用程序在舊版本上運行的應用程序,就像我曾經使用的那樣。 – user2602152