selenium+phantomjs报错:Unable to find a free port的分析和解决


selenium+phantomjs报错:Unable to find a free port的分析和解决

Table of Contents

1 现象

在做项目时,发现在某台机器上使用selenium+phantomjs时报如下错误:

java.lang.RuntimeException: Unable to find a free port
        at org.openqa.selenium.net.PortProber.findFreePort(PortProber.java:67)
        at org.openqa.selenium.phantomjs.PhantomJSDriverService$Builder.build(PhantomJSDriverService.java:443)
        ...

2 分析

通过跟踪源代码(org.openqa.selenium.net.PortProber.createAcceptablePort),发现:

if (FIRST_PORT == LAST_PORT) {
        return FIRST_PORT;
}

在该服务器上,FIRSTPORT = LASTPORT = 1024,因此总是返回1024。

查看服务器的可用本地端口配置,如下:

[gyx@interface01 ~]$ cat /proc/sys/net/ipv4/ip_local_port_range
1024	65535

因为这台机器的最低可用端口配置成了1024,而其他机器都比这个大很多,因此造成了上述问题。

3 解决办法

因为该服务器还有别的用处,不能随意修改可用端口配置,所以,暂时通过修改createAcceptablePort中相应代码解决问题。如下:

if (FIRST_PORT == LAST_PORT) {
//                return FIRST_PORT;
        final int randomInt = random.nextInt();
        System.out.println("randomInt = " + randomInt);
        final int portWithoutOffset = Math.abs(randomInt % (HIGHEST_PORT - START_OF_USER_PORTS + 1));
        return portWithoutOffset + FIRST_PORT;
}

Author: galaxy

Created: 2016-07-28 Thu 09:58

Emacs 24.5.6 (Org mode 8.2.10)

Validate

posted @ 2016-07-28 10:01  galaxy-gao  阅读(2315)  评论(0编辑  收藏  举报