當前位置:首頁 » 雲伺服器 » java獲取伺服器地址

java獲取伺服器地址

發布時間: 2022-01-11 23:59:38

A. java中伺服器端ServerSocket對象怎麼獲取伺服器端地址和埠號,怎麼獲取遠程請求的

ServerSocket s = new ServerSocket(8888);
while (true) {
// 建立連接
Socket socket = s.accept();

/ /getInetAddress()獲取遠程ip地址,getPort()遠程客戶端的斷後好
"你好,客戶端地址信息: " + socket.getInetAddress() + "\t客戶端通信埠號: " + socket.getPort()

B. java裡面如何獲取伺服器的ip地址,幫幫忙

獲取本機ip地址
InetAddress addr = InetAddress.getLocalHost();
ip=addr.getHostAddress().toString;

C. java 如何把伺服器獲取的ip地址和主機名寫入TXT文件

給你一個方法,自己調一下吧.

host就是主機名

ip就是ip,

filepath就是文件路徑

	publicvoidcreateFile(Stringhost,Stringip,Stringfilepath)
{
BufferedWriterbw=null;
try{
bw=newBufferedWriter(newFileWriter(newFile(filepath)));
bw.write("host-name:"+host+",ip:"+ip);
bw.flush();
bw.close();
}catch(IOExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
}

D. JAVA如何獲得伺服器端重定向後的URL

request.getHeader("REDIRECT_URL");

或試試
那在servlet里邊或者action調用request.getRequestURL()就是了。
如果是獲得容器內部的請求URI:request.getRequestURI(),兩個方法挺象的。

E. 如何通過Java代碼獲取tomcat伺服器的絕對路徑

//也許有你想要的,前提是在項目布署運行起來後,在servlet中或controller中運行以下代碼即可。
System.out.println(this.getClass().getResource("/"));//結果:file:/E:/work/service/tomcat7.0.65/webapps/mvc_adminlte/WEB-INF/classes/
System.out.println(System.getProperty("catalina.home"));//結果:E:workservice omcat7.0.65
System.getProperty("user.dir");//結果:E:workservice omcat7.0.65in
System.out.println(request.getSession().getServletContext().getRealPath("/"));//結果:E:workservice omcat7.0.65webapps你的項目名稱
希望能幫到你!

F. JAVA怎麼獲取伺服器IP

首先IP為一個字元串,例如:
class test{
static void Split(string ip,out string str1)
{
int i=ip.length;
while(i>0)
{
char ch=ip[i-1];
if(ch==':')
break;
i--;
}
str1=ip.Substring(0,i);
}
static void Main()
{
string str1;
Split("192.168.0.255:8080",out str1)
Console.WriteLine("{0}",str1);
}
}
str1中保存的就是你的ip,192.168.0.255

G. java獲取伺服器文件,怎樣用url返回

下面提供二種方法會使用java發送url請求,並獲取伺服器返回的值

第一種方法:
代碼如下:

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;

(StringurlStr,Stringparam1,Stringparam2)throwsException{
StringtempStr=null;
HttpClienthttpclient=newDefaultHttpClient();
Propertiesproperties=newProperties();
HttpEntityentity=null;
StringxmlContent="";
try
{

//設置超時時間
httpclient.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,20000);
httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,20000);

//封裝需要傳遞的參數
List<NameValuePair>nvps=newArrayList<NameValuePair>();
nvps.add(newBasicNameValuePair("mainMemoCode",strmainMemoCode));
nvps.add(newBasicNameValuePair("recordPassWord",strrecordPassWord));
//客戶端的請求方法類型
HttpPosthttpPost=newHttpPost(urlStr);
httpPost.setEntity(newUrlEncodedFormEntity(nvps,"GBK"));
HttpResponseresponse=httpclient.execute(httpPost);

//獲取伺服器返回Http的Content-Type的值
tempStr=response.getHeaders("Content-Type")[0].getValue().toString();

//獲取伺服器返回頁面的值
entity=response.getEntity();
xmlContent=EntityUtils.toString(entity);
Stringstrmessage=null;
System.out.println(xmlContent);
System.out.println(response.getHeaders("Content-Type")[0].getValue().toString());
httpPost.abort();

}
catch(SocketTimeoutExceptione)
{
}
catch(Exceptionex)
{
ex.printStackTrace();
}
finally{
httpclient.getConnectionManager().shutdown();
}
第二種方法:

代碼如下:


(StringurlStr,Stringparam1,Stringparam2)throwsException{

HttpURLConnectionurl_con=null;
try{
URLurl=newURL(urlStr);
StringBufferbankXmlBuffer=newStringBuffer();
//創建URL連接,提交到數據,獲取返回結果
HttpURLConnectionconnection=(HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty("User-Agent","directclient");

PrintWriterout=newPrintWriter(newOutputStreamWriter(connection.getOutputStream(),"GBK"));
out.println(param);
out.close();
BufferedReaderin=newBufferedReader(newInputStreamReader(connection
.getInputStream(),"GBK"));

StringinputLine;

while((inputLine=in.readLine())!=null){
bankXmlBuffer.append(inputLine);
}
in.close();
tempStr=bankXmlBuffer.toString();
}
catch(Exceptione)
{
System.out.println("發送GET請求出現異常!"+e);
e.printStackTrace();

}finally{
if(url_con!=null)
url_con.disconnect();
}

returntmpeStr;
}

總結:多練習代碼,熟練之後才能更快速的去了解代碼的學習的方法。多去獲取一些思維方面的書籍可以看看。

H. 在Java中如何得到本地IP和伺服器的機器名

import java.net.*; public class catchserverip{ InetAddress ServerIPaddress=null; //取得Server的IP地址 public InetAddress getServerIP() { try { ServerIPaddress=InetAddress.getLocalHost();} catch (UnknownHostException e) {} return (ServerIPaddress);}}就可以了在jsp中寫 <jsp:useBean id=catchipbean scope=page class=catchip / String servername=catchipbean.getServerIP().getHostName(); ---------------------------------------------------------------

I. java編程,獲取區域網內伺服器端的ip地址

socket.connect(new InetSocketAddress(ip, port), timeout)

看有沒有拋異常 沒異常就是已經連接上了

想獲取伺服器名稱 可以用ARP協議 或者測試連接的時候伺服器回應一個名稱

package;

importjava.io.IOException;
importjava.net.InetSocketAddress;
importjava.net.Socket;

publicclassClient{

publicstaticvoidmain(String[]args){
/**
*埠號
*/
intport=10000;
/**
*連接延時
*/
inttimeout=300;
System.out.println("ScannerStart...");
Socketsocket;
/**
*掃描
*/
for(inti=1,k=254;i<k;i++){
if((socket=isOnLine("192.168.1."+i,port,timeout))!=null){
System.out.println("Server:"
+socket.getInetAddress().getHostAddress()
+":"+socket.getPort()+"IsWaiting...");
}

/**
*關閉連接
*/
if(socket!=null&&!socket.isClosed()){
try{
socket.close();
}catch(IOExceptione){
socket=null;
}
}
}
System.out.println("Scannerend...");
}

/**
*測試連接伺服器,返回連接成功後的Socket
*
*@paramip
*伺服器Ip
*@paramport
*伺服器埠號
*@paramtimeout
*連接延時
*@return返回連接成功後的Socket
*/
privatestaticSocketisOnLine(Stringip,intport,inttimeout){
Socketsocket=newSocket();
try{
socket.connect(newInetSocketAddress(ip,port),timeout);
}catch(IOExceptione){
returnnull;
}
returnsocket;
}

}

J. java 怎麼獲取伺服器webroot的路徑

使用JAVA後台代碼取得WEBROOT物理路徑,可以有如下兩種方式:
1、使用JSP Servlet取得WEB根路徑可以用request.getContextPath(),相對路徑request.getSession().getServletContext().getRealPath("/"),它們可以使用我們很容易取得根路徑。

2、如果使用了spring, 在WEB-INF/web.xml中,創建一個webAppRootKey的param,指定一個值(默認為webapp.root)作為鍵值,然後通過Listener,或者Filter,或者Servlet執行String webAppRootKey = getServletContext().getRealPath("/"); 並將webAppRootKey對應的webapp.root分別作為Key,Value寫到System Properties系統屬性中。之後在程序中通過System.getProperty("webapp.root")來獲得WebRoot的物理路徑。
具體示例代碼如下:
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<context-param>
<param-name>webAppRootKey</param-name>
<param-value>csc2.root</param-value>
</context-param>
<listener>
<listener-class>test.ApplicationListener</listener-class>
</listener>
</web-app>

ApplicationListener.java
package test;
import javax.servlet.ServletContextEvent;
import org.springframework.web.context.ContextLoaderListener;
public class ApplicationListener extends ContextLoaderListener {
public void contextDestroyed(ServletContextEvent sce) {
// TODO Auto-generated method stub
}
public void contextInitialized(ServletContextEvent sce) {
// TODO Auto-generated method stub
String webAppRootKey = sce.getServletContext().getRealPath("/");
System.setProperty("csc2.root" , webAppRootKey);
String path =System.getProperty("csc2.root");
System.out.println("sssss:::"+path);
}
}

test.java
public class test {
public void remve(){
String path =System.getProperty("csc2.root");
System.out.println("result::::::::"+path);
}

}

index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ page import="java.util.*" %>
<%@ page import="test.test" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%
test t = new test();
t.remve();
%>
<html>
</html>
部署程序發布 啟動TOMCAT 運行index.jsp 就可以調用JAVA中全局設置的物理路徑了(說明這里的JSP 只是調用了TEST.JAVA 的remove方法,不做其他使用。原理解釋,TOMCAT啟動和讀取WEB.XML 監聽方式載入SPRING ApplicationListener繼承SPRING ContextLoaderListener載入SPRING順便吧全局路徑賦值給csc2.root 描述,這樣之後JAVA 代碼中就可以使用System.getProperty("csc2.root")調用全路路徑了。

熱點內容
ios應用上傳 發布:2024-09-08 09:39:41 瀏覽:439
ios儲存密碼哪裡看 發布:2024-09-08 09:30:02 瀏覽:873
opensslcmake編譯 發布:2024-09-08 09:08:48 瀏覽:653
linux下ntp伺服器搭建 發布:2024-09-08 08:26:46 瀏覽:744
db2新建資料庫 發布:2024-09-08 08:10:19 瀏覽:173
頻率計源碼 發布:2024-09-08 07:40:26 瀏覽:780
奧迪a6哪個配置帶後排加熱 發布:2024-09-08 07:06:32 瀏覽:101
linux修改apache埠 發布:2024-09-08 07:05:49 瀏覽:209
有多少個不同的密碼子 發布:2024-09-08 07:00:46 瀏覽:566
linux搭建mysql伺服器配置 發布:2024-09-08 06:50:02 瀏覽:995